From d5b36530120ba025e050e3acb2f124653dd812be Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sun, 15 Nov 2026 22:46:12 -0500 Subject: [PATCH] feat: deploy scoped grpc data connection configuration --- .../Entities/DataConnection.cs | 32 + .../Entities/DataExport.cs | 23 + .../Entities/RemoteNamespaceMapping.cs | 36 + .../Enums/NodeAclScopeKind.cs | 5 +- ...6030721_AddGrpcDataConnections.Designer.cs | 1946 +++++++++++++++++ .../20261116030721_AddGrpcDataConnections.cs | 195 ++ .../OtOpcUaConfigDbContextModelSnapshot.cs | 332 ++- .../OtOpcUaConfigDbContext.cs | 63 +- .../Validation/DataConnectionValidator.cs | 274 +++ .../Validation/DraftSnapshot.cs | 5 + .../Validation/DraftSnapshotFactory.cs | 3 + .../Validation/DraftValidator.cs | 4 + .../AdminOperations/ConfigComposer.cs | 22 + .../DeploymentArtifact.DataConnections.cs | 313 +++ .../Drivers/DeploymentArtifact.cs | 4 +- .../GrpcDataConfigurationTests.cs | 76 + .../GrpcDataMappingValidationTests.cs | 95 + .../GrpcDataSchemaModelTests.cs | 44 + .../GrpcDataArtifactProjectionTests.cs | 228 ++ .../GrpcDataArtifactReadTests.cs | 496 +++++ 20 files changed, 4190 insertions(+), 6 deletions(-) create mode 100644 src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataConnection.cs create mode 100644 src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataExport.cs create mode 100644 src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/RemoteNamespaceMapping.cs create mode 100644 src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116030721_AddGrpcDataConnections.Designer.cs create mode 100644 src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116030721_AddGrpcDataConnections.cs create mode 100644 src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataConfigurationTests.cs create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataMappingValidationTests.cs create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataSchemaModelTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DataConnections/GrpcDataArtifactProjectionTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataConnection.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataConnection.cs new file mode 100644 index 000000000..496b757e4 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataConnection.cs @@ -0,0 +1,32 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Entities; + +/// A directional, node-scoped connection to an expected data-service identity. +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 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 EligibleTargetNodeIds { get; set; } = []; + public List Endpoints { get; set; } = []; + /// Non-secret reference; its value is resolved on consumer nodes. + 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; } = []; +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataExport.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataExport.cs new file mode 100644 index 000000000..c3f12fe5b --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataExport.cs @@ -0,0 +1,23 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Entities; + +/// Origin-local export grant for a named authenticated peer principal. +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; } = []; +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/RemoteNamespaceMapping.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/RemoteNamespaceMapping.cs new file mode 100644 index 000000000..24c12bad1 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/RemoteNamespaceMapping.cs @@ -0,0 +1,36 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Entities; + +/// A local realm-qualified branch projection, not a synthetic locally owned tag. +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 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; } = ""; + /// Optional leaf type expectation; branch types are verified as catalog metadata arrives. + 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; } = []; +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Enums/NodeAclScopeKind.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Enums/NodeAclScopeKind.cs index 104e48f4b..e1af9df80 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Enums/NodeAclScopeKind.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Enums/NodeAclScopeKind.cs @@ -3,7 +3,7 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Enums; /// ACL scope level. Per acl-design.md §"Scope Hierarchy". /// /// ⚠️ Append new members only — never insert. SQL Server stores this as a string -/// (nvarchar(16), so a member name must also stay ≤ 16 characters), but the deployment +/// (nvarchar(32), so a member name must also stay ≤ 32 characters), but the deployment /// artifact serialises it as the integer ordinal and the node-side decoder reads it back /// with Enum.IsDefined. 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 /// A raw-tree tag group. ScopeId is a TagGroup.TagGroupId. (v3; appended.) RawTagGroup, + + /// A realm-qualified remote mapping, scoped by its logical ID. + RemoteNamespaceMapping, } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116030721_AddGrpcDataConnections.Designer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116030721_AddGrpcDataConnections.Designer.cs new file mode 100644 index 000000000..55a98634d --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116030721_AddGrpcDataConnections.Designer.cs @@ -0,0 +1,1946 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using ZB.MOM.WW.OtOpcUa.Configuration; + +#nullable disable + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations +{ + [DbContext(typeof(OtOpcUaConfigDbContext))] + [Migration("20261116030721_AddGrpcDataConnections")] + partial class AddGrpcDataConnections + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.7") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("FriendlyName") + .HasColumnType("nvarchar(max)"); + + b.Property("Xml") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("DataProtectionKeys", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ApiKey", b => + { + b.Property("ApiKeyRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ApiKeyId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedUtc") + .HasColumnType("datetime2"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("ExpiresUtc") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Principal") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SecretHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("ApiKeyRowId"); + + b.HasIndex("ApiKeyId") + .IsUnique() + .HasDatabaseName("UX_ApiKey_ApiKeyId"); + + b.HasIndex("Principal") + .HasDatabaseName("IX_ApiKey_Principal"); + + b.ToTable("ApiKey", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", b => + { + b.Property("NodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("AkkaPort") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(4053); + + b.Property("ApplicationUri") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("DashboardPort") + .HasColumnType("int"); + + b.Property("DriverConfigOverridesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GrpcPort") + .HasColumnType("int"); + + b.Property("Host") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("LastSeenAt") + .HasColumnType("datetime2(3)"); + + b.Property("MaintenanceMode") + .HasColumnType("bit"); + + b.Property("OpcUaPort") + .HasColumnType("int"); + + b.Property("ServiceLevelBase") + .HasColumnType("tinyint"); + + b.HasKey("NodeId"); + + b.HasIndex("ApplicationUri") + .IsUnique() + .HasDatabaseName("UX_ClusterNode_ApplicationUri"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_ClusterNode_ClusterId"); + + b.ToTable("ClusterNode", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNodeCredential", b => + { + b.Property("CredentialId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("NodeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RotatedAt") + .HasColumnType("datetime2(3)"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.HasKey("CredentialId"); + + b.HasIndex("Kind", "Value") + .IsUnique() + .HasDatabaseName("UX_ClusterNodeCredential_Value") + .HasFilter("[Enabled] = 1"); + + b.HasIndex("NodeId", "Enabled") + .HasDatabaseName("IX_ClusterNodeCredential_NodeId"); + + b.ToTable("ClusterNodeCredential", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ConfigAuditLog", b => + { + b.Property("AuditId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("AuditId")); + + b.Property("ClusterId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CorrelationId") + .HasColumnType("uniqueidentifier"); + + b.Property("DetailsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("EventId") + .HasColumnType("uniqueidentifier"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("GenerationId") + .HasColumnType("bigint"); + + b.Property("NodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Outcome") + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("Principal") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Timestamp") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.HasKey("AuditId"); + + b.HasIndex("EventId") + .IsUnique() + .HasDatabaseName("UX_ConfigAuditLog_EventId") + .HasFilter("[EventId] IS NOT NULL"); + + b.HasIndex("GenerationId") + .HasDatabaseName("IX_ConfigAuditLog_Generation") + .HasFilter("[GenerationId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Timestamp") + .IsDescending(false, true) + .HasDatabaseName("IX_ConfigAuditLog_Cluster_Time"); + + b.ToTable("ConfigAuditLog", null, t => + { + t.HasCheckConstraint("CK_ConfigAuditLog_DetailsJson_IsJson", "DetailsJson IS NULL OR ISJSON(DetailsJson) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ConfigEdit", b => + { + b.Property("EditId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("EditedAtUtc") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("EditedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("EntityId") + .HasColumnType("uniqueidentifier"); + + b.Property("EntityType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ExecutionId") + .HasColumnType("uniqueidentifier"); + + b.Property("FieldsJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("SourceNode") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("EditId"); + + b.HasIndex("EditedAtUtc") + .HasDatabaseName("IX_ConfigEdit_EditedAt"); + + b.HasIndex("ExecutionId") + .HasDatabaseName("IX_ConfigEdit_Execution") + .HasFilter("[ExecutionId] IS NOT NULL"); + + b.HasIndex("EntityType", "EntityId") + .HasDatabaseName("IX_ConfigEdit_Entity"); + + b.ToTable("ConfigEdit", null, t => + { + t.HasCheckConstraint("CK_ConfigEdit_FieldsJson_IsJson", "ISJSON(FieldsJson) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection", b => + { + b.Property("DataConnectionRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowedOperations") + .HasColumnType("int"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Consistency") + .HasColumnType("int"); + + b.PrimitiveCollection("ConsumerNodeIds") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DataConnectionId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.PrimitiveCollection("EligibleTargetNodeIds") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.PrimitiveCollection("Endpoints") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ExpectedClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ExpectedNodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("MaxBatchItems") + .HasColumnType("int"); + + b.Property("MaxMessageBytes") + .HasColumnType("int"); + + b.Property("MaxMonitoredItems") + .HasColumnType("int"); + + b.Property("MaxPageItems") + .HasColumnType("int"); + + b.Property("MaxPendingBytes") + .HasColumnType("bigint"); + + b.Property("MaxStreams") + .HasColumnType("int"); + + b.Property("Revision") + .HasColumnType("bigint"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SecretReference") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("SecretScopeClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("TargetMode") + .HasColumnType("int"); + + b.Property("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("DataExportRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowedOperations") + .HasColumnType("int"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DataExportId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("MaxBatchItems") + .HasColumnType("int"); + + b.Property("MaxMonitoredItems") + .HasColumnType("int"); + + b.Property("MaxPageItems") + .HasColumnType("int"); + + b.Property("MaxStreams") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Realm") + .HasColumnType("int"); + + b.Property("Revision") + .HasColumnType("bigint"); + + b.Property("RootEntityId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RootKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("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("DeploymentId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ArtifactBlob") + .IsRequired() + .HasColumnType("varbinary(max)"); + + b.Property("CreatedAtUtc") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("FailureReason") + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("RevisionHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SealedAtUtc") + .HasColumnType("datetime2(3)"); + + b.Property("Status") + .HasColumnType("int"); + + b.HasKey("DeploymentId"); + + b.HasIndex("CreatedAtUtc") + .HasDatabaseName("IX_Deployment_CreatedAt"); + + b.HasIndex("Status") + .HasDatabaseName("IX_Deployment_Status"); + + b.ToTable("Deployment", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Device", b => + { + b.Property("DeviceRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DeviceConfig") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DriverInstanceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("DeviceRowId"); + + b.HasIndex("DeviceId") + .IsUnique() + .HasDatabaseName("UX_Device_LogicalId") + .HasFilter("[DeviceId] IS NOT NULL"); + + b.HasIndex("DriverInstanceId") + .HasDatabaseName("IX_Device_Driver"); + + b.HasIndex("DriverInstanceId", "Name") + .IsUnique() + .HasDatabaseName("UX_Device_Driver_Name"); + + b.ToTable("Device", null, t => + { + t.HasCheckConstraint("CK_Device_DeviceConfig_IsJson", "ISJSON(DeviceConfig) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DriverInstance", b => + { + b.Property("DriverInstanceRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DriverConfig") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DriverInstanceId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DriverType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RawFolderId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ResilienceConfig") + .HasColumnType("nvarchar(max)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("DriverInstanceRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_DriverInstance_Cluster"); + + b.HasIndex("DriverInstanceId") + .IsUnique() + .HasDatabaseName("UX_DriverInstance_LogicalId") + .HasFilter("[DriverInstanceId] IS NOT NULL"); + + b.HasIndex("RawFolderId") + .HasDatabaseName("IX_DriverInstance_RawFolder"); + + b.HasIndex("ClusterId", "Name") + .IsUnique() + .HasDatabaseName("UX_DriverInstance_ClusterRoot_Name") + .HasFilter("[RawFolderId] IS NULL"); + + b.HasIndex("ClusterId", "RawFolderId", "Name") + .IsUnique() + .HasDatabaseName("UX_DriverInstance_Folder_Name") + .HasFilter("[RawFolderId] IS NOT NULL"); + + b.ToTable("DriverInstance", null, t => + { + t.HasCheckConstraint("CK_DriverInstance_DriverConfig_IsJson", "ISJSON(DriverConfig) = 1"); + + t.HasCheckConstraint("CK_DriverInstance_ResilienceConfig_IsJson", "ResilienceConfig IS NULL OR ISJSON(ResilienceConfig) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Equipment", b => + { + b.Property("EquipmentRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AssetLocation") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("DeviceManualUri") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("EquipmentClassRef") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("EquipmentId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("EquipmentUuid") + .HasColumnType("uniqueidentifier"); + + b.Property("HardwareRevision") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("MachineCode") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Manufacturer") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ManufacturerUri") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Model") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SAPID") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("SerialNumber") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("SoftwareRevision") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("UnsLineId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("YearOfConstruction") + .HasColumnType("smallint"); + + b.Property("ZTag") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("EquipmentRowId"); + + b.HasIndex("EquipmentId") + .IsUnique() + .HasDatabaseName("UX_Equipment_LogicalId") + .HasFilter("[EquipmentId] IS NOT NULL"); + + b.HasIndex("EquipmentUuid") + .IsUnique() + .HasDatabaseName("UX_Equipment_Uuid"); + + b.HasIndex("MachineCode") + .HasDatabaseName("IX_Equipment_MachineCode"); + + b.HasIndex("SAPID") + .HasDatabaseName("IX_Equipment_SAPID") + .HasFilter("[SAPID] IS NOT NULL"); + + b.HasIndex("UnsLineId") + .HasDatabaseName("IX_Equipment_Line"); + + b.HasIndex("ZTag") + .HasDatabaseName("IX_Equipment_ZTag") + .HasFilter("[ZTag] IS NOT NULL"); + + b.HasIndex("UnsLineId", "Name") + .IsUnique() + .HasDatabaseName("UX_Equipment_LinePath"); + + b.ToTable("Equipment", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ExternalIdReservation", b => + { + b.Property("ReservationId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("EquipmentUuid") + .HasColumnType("uniqueidentifier"); + + b.Property("FirstPublishedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("FirstPublishedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("LastPublishedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("ReleaseReason") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("ReleasedAt") + .HasColumnType("datetime2(3)"); + + b.Property("ReleasedBy") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("ReservationId"); + + b.HasIndex("EquipmentUuid") + .HasDatabaseName("IX_ExternalIdReservation_Equipment"); + + b.HasIndex("Kind", "Value") + .IsUnique() + .HasDatabaseName("UX_ExternalIdReservation_KindValue_Active") + .HasFilter("[ReleasedAt] IS NULL"); + + b.ToTable("ExternalIdReservation", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.LdapGroupRoleMapping", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClusterId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedAtUtc") + .HasColumnType("datetime2(3)"); + + b.Property("IsSystemWide") + .HasColumnType("bit"); + + b.Property("LdapGroup") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("ClusterId"); + + b.HasIndex("LdapGroup") + .HasDatabaseName("IX_LdapGroupRoleMapping_Group"); + + b.HasIndex("LdapGroup", "ClusterId") + .IsUnique() + .HasDatabaseName("UX_LdapGroupRoleMapping_Group_Cluster") + .HasFilter("[ClusterId] IS NOT NULL"); + + b.ToTable("LdapGroupRoleMapping", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.NodeAcl", b => + { + b.Property("NodeAclRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("NodeAclId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PermissionFlags") + .HasColumnType("int"); + + b.Property("Principal") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScopeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ScopeKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("NodeAclRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_NodeAcl_Cluster"); + + b.HasIndex("NodeAclId") + .IsUnique() + .HasDatabaseName("UX_NodeAcl_LogicalId") + .HasFilter("[NodeAclId] IS NOT NULL"); + + b.HasIndex("Principal") + .HasDatabaseName("IX_NodeAcl_Principal"); + + b.HasIndex("ScopeKind", "ScopeId") + .HasDatabaseName("IX_NodeAcl_Scope") + .HasFilter("[ScopeId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Principal", "ScopeKind", "ScopeId") + .IsUnique() + .HasDatabaseName("UX_NodeAcl_PrincipalScope") + .HasFilter("[ScopeId] IS NOT NULL"); + + b.ToTable("NodeAcl", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.NodeDeploymentState", b => + { + b.Property("NodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DeploymentId") + .HasColumnType("uniqueidentifier"); + + b.Property("AppliedAtUtc") + .HasColumnType("datetime2(3)"); + + b.Property("FailureReason") + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("StartedAtUtc") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("Status") + .HasColumnType("int"); + + b.HasKey("NodeId", "DeploymentId"); + + b.HasIndex("DeploymentId") + .HasDatabaseName("IX_NodeDeploymentState_Deployment"); + + b.HasIndex("Status") + .HasDatabaseName("IX_NodeDeploymentState_Status"); + + b.ToTable("NodeDeploymentState", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.PollGroup", b => + { + b.Property("PollGroupRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DriverInstanceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("IntervalMs") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PollGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("PollGroupRowId"); + + b.HasIndex("DriverInstanceId") + .HasDatabaseName("IX_PollGroup_Driver"); + + b.HasIndex("PollGroupId") + .IsUnique() + .HasDatabaseName("UX_PollGroup_LogicalId") + .HasFilter("[PollGroupId] IS NOT NULL"); + + b.ToTable("PollGroup", null, t => + { + t.HasCheckConstraint("CK_PollGroup_IntervalMs_Min", "IntervalMs >= 50"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RawFolder", b => + { + b.Property("RawFolderRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ParentRawFolderId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RawFolderId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.HasKey("RawFolderRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_RawFolder_Cluster"); + + b.HasIndex("RawFolderId") + .IsUnique() + .HasDatabaseName("UX_RawFolder_LogicalId") + .HasFilter("[RawFolderId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Name") + .IsUnique() + .HasDatabaseName("UX_RawFolder_ClusterRoot_Name") + .HasFilter("[ParentRawFolderId] IS NULL"); + + b.HasIndex("ClusterId", "ParentRawFolderId", "Name") + .IsUnique() + .HasDatabaseName("UX_RawFolder_Parent_Name") + .HasFilter("[ParentRawFolderId] IS NOT NULL"); + + b.ToTable("RawFolder", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RemoteNamespaceMapping", b => + { + b.Property("RemoteNamespaceMappingRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowedOperations") + .HasColumnType("int"); + + b.Property("BranchName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.PrimitiveCollection("ConsumerNodeIds") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DataConnectionId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("ExpectedArrayElementKind") + .HasColumnType("int"); + + b.Property("ExpectedValueKind") + .HasColumnType("int"); + + b.Property("LocalParentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("LocalParentKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("MaxProjectionDepth") + .HasColumnType("int"); + + b.Property("MaxProjectionNodes") + .HasColumnType("int"); + + b.Property("MetadataLeaseMilliseconds") + .HasColumnType("int"); + + b.Property("PublishingIntervalMilliseconds") + .HasColumnType("int"); + + b.Property("Realm") + .HasColumnType("int"); + + b.Property("RemoteIdentifier") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RemoteIdentifierKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("RemoteNamespaceMappingId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RemoteNamespaceUri") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RemoteRealm") + .HasColumnType("int"); + + b.Property("RemoteRootEntityId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Revision") + .HasColumnType("bigint"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SamplingIntervalMilliseconds") + .HasColumnType("int"); + + b.Property("StaleTimeoutMilliseconds") + .HasColumnType("int"); + + b.Property("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("ScriptRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("Language") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScriptId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("SourceCode") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("SourceHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("ScriptRowId"); + + b.HasIndex("ScriptId") + .IsUnique() + .HasDatabaseName("UX_Script_LogicalId") + .HasFilter("[ScriptId] IS NOT NULL"); + + b.HasIndex("SourceHash") + .HasDatabaseName("IX_Script_SourceHash"); + + b.ToTable("Script", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ScriptedAlarm", b => + { + b.Property("ScriptedAlarmRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AlarmType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("EquipmentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("HistorizeToAveva") + .HasColumnType("bit"); + + b.Property("MessageTemplate") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PredicateScriptId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Retain") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScriptedAlarmId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Severity") + .HasColumnType("int"); + + b.HasKey("ScriptedAlarmRowId"); + + b.HasIndex("PredicateScriptId") + .HasDatabaseName("IX_ScriptedAlarm_Script"); + + b.HasIndex("ScriptedAlarmId") + .IsUnique() + .HasDatabaseName("UX_ScriptedAlarm_LogicalId") + .HasFilter("[ScriptedAlarmId] IS NOT NULL"); + + b.HasIndex("EquipmentId", "Name") + .IsUnique() + .HasDatabaseName("UX_ScriptedAlarm_EquipmentPath"); + + b.ToTable("ScriptedAlarm", null, t => + { + t.HasCheckConstraint("CK_ScriptedAlarm_AlarmType", "AlarmType IN ('AlarmCondition','LimitAlarm','OffNormalAlarm','DiscreteAlarm')"); + + t.HasCheckConstraint("CK_ScriptedAlarm_Severity_Range", "Severity BETWEEN 1 AND 1000"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", b => + { + b.Property("ClusterId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Enterprise") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("ModifiedAt") + .HasColumnType("datetime2(3)"); + + b.Property("ModifiedBy") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("NodeCount") + .HasColumnType("tinyint"); + + b.Property("Notes") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("RedundancyMode") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("Site") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("ClusterId"); + + b.HasIndex("Name") + .IsUnique() + .HasDatabaseName("UX_ServerCluster_Name"); + + b.HasIndex("Site") + .HasDatabaseName("IX_ServerCluster_Site"); + + b.ToTable("ServerCluster", null, t => + { + t.HasCheckConstraint("CK_ServerCluster_RedundancyMode_NodeCount", "((NodeCount = 1 AND RedundancyMode = 'None') OR (NodeCount = 2 AND RedundancyMode IN ('Warm', 'Hot')))"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Tag", b => + { + b.Property("TagRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AccessLevel") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("DataType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("DeviceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PollGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TagConfig") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TagGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("TagId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("WriteIdempotent") + .HasColumnType("bit"); + + b.HasKey("TagRowId"); + + b.HasIndex("TagId") + .IsUnique() + .HasDatabaseName("UX_Tag_LogicalId") + .HasFilter("[TagId] IS NOT NULL"); + + b.HasIndex("DeviceId", "Name") + .IsUnique() + .HasDatabaseName("UX_Tag_Device_Name") + .HasFilter("[TagGroupId] IS NULL"); + + b.HasIndex("DeviceId", "TagGroupId") + .HasDatabaseName("IX_Tag_Device"); + + b.HasIndex("DeviceId", "TagGroupId", "Name") + .IsUnique() + .HasDatabaseName("UX_Tag_Group_Name") + .HasFilter("[TagGroupId] IS NOT NULL"); + + b.ToTable("Tag", null, t => + { + t.HasCheckConstraint("CK_Tag_TagConfig_IsJson", "ISJSON(TagConfig) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.TagGroup", b => + { + b.Property("TagGroupRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DeviceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ParentTagGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.Property("TagGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("TagGroupRowId"); + + b.HasIndex("DeviceId") + .HasDatabaseName("IX_TagGroup_Device"); + + b.HasIndex("TagGroupId") + .IsUnique() + .HasDatabaseName("UX_TagGroup_LogicalId") + .HasFilter("[TagGroupId] IS NOT NULL"); + + b.HasIndex("DeviceId", "Name") + .IsUnique() + .HasDatabaseName("UX_TagGroup_DeviceRoot_Name") + .HasFilter("[ParentTagGroupId] IS NULL"); + + b.HasIndex("DeviceId", "ParentTagGroupId", "Name") + .IsUnique() + .HasDatabaseName("UX_TagGroup_Parent_Name") + .HasFilter("[ParentTagGroupId] IS NOT NULL"); + + b.ToTable("TagGroup", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsArea", b => + { + b.Property("UnsAreaRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("UnsAreaId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("UnsAreaRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_UnsArea_Cluster"); + + b.HasIndex("UnsAreaId") + .IsUnique() + .HasDatabaseName("UX_UnsArea_LogicalId") + .HasFilter("[UnsAreaId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Name") + .IsUnique() + .HasDatabaseName("UX_UnsArea_ClusterName"); + + b.ToTable("UnsArea", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsLine", b => + { + b.Property("UnsLineRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("UnsAreaId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("UnsLineId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("UnsLineRowId"); + + b.HasIndex("UnsAreaId") + .HasDatabaseName("IX_UnsLine_Area"); + + b.HasIndex("UnsLineId") + .IsUnique() + .HasDatabaseName("UX_UnsLine_LogicalId") + .HasFilter("[UnsLineId] IS NOT NULL"); + + b.HasIndex("UnsAreaId", "Name") + .IsUnique() + .HasDatabaseName("UX_UnsLine_AreaName"); + + b.ToTable("UnsLine", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsTagReference", b => + { + b.Property("UnsTagReferenceRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DisplayNameOverride") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("EquipmentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.Property("TagId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("UnsTagReferenceId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("UnsTagReferenceRowId"); + + b.HasIndex("EquipmentId") + .HasDatabaseName("IX_UnsTagReference_Equipment"); + + b.HasIndex("TagId") + .HasDatabaseName("IX_UnsTagReference_Tag"); + + b.HasIndex("UnsTagReferenceId") + .IsUnique() + .HasDatabaseName("UX_UnsTagReference_LogicalId") + .HasFilter("[UnsTagReferenceId] IS NOT NULL"); + + b.HasIndex("EquipmentId", "TagId") + .IsUnique() + .HasDatabaseName("UX_UnsTagReference_Equip_Tag"); + + b.ToTable("UnsTagReference", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.VirtualTag", b => + { + b.Property("VirtualTagRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ChangeTriggered") + .HasColumnType("bit"); + + b.Property("DataType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("EquipmentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Historize") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScriptId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("TimerIntervalMs") + .HasColumnType("int"); + + b.Property("VirtualTagId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("VirtualTagRowId"); + + b.HasIndex("ScriptId") + .HasDatabaseName("IX_VirtualTag_Script"); + + b.HasIndex("VirtualTagId") + .IsUnique() + .HasDatabaseName("UX_VirtualTag_LogicalId") + .HasFilter("[VirtualTagId] IS NOT NULL"); + + b.HasIndex("EquipmentId", "Name") + .IsUnique() + .HasDatabaseName("UX_VirtualTag_EquipmentPath"); + + b.ToTable("VirtualTag", null, t => + { + t.HasCheckConstraint("CK_VirtualTag_TimerInterval_Min", "TimerIntervalMs IS NULL OR TimerIntervalMs >= 50"); + + t.HasCheckConstraint("CK_VirtualTag_Trigger_AtLeastOne", "ChangeTriggered = 1 OR TimerIntervalMs IS NOT NULL"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster") + .WithMany("Nodes") + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNodeCredential", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", "Node") + .WithMany("Credentials") + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + 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") + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.LdapGroupRoleMapping", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster") + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.NodeDeploymentState", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Deployment", "Deployment") + .WithMany() + .HasForeignKey("DeploymentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", "Node") + .WithMany() + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Deployment"); + + b.Navigation("Node"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RawFolder", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null) + .WithMany("RawFolders") + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .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") + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", b => + { + b.Navigation("Credentials"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", b => + { + b.Navigation("Nodes"); + + b.Navigation("RawFolders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116030721_AddGrpcDataConnections.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116030721_AddGrpcDataConnections.cs new file mode 100644 index 000000000..fe8d3e494 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116030721_AddGrpcDataConnections.cs @@ -0,0 +1,195 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations +{ + /// + public partial class AddGrpcDataConnections : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + 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(type: "uniqueidentifier", nullable: false, defaultValueSql: "NEWSEQUENTIALID()"), + DataConnectionId = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: true), + ClusterId = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + Revision = table.Column(type: "bigint", nullable: false), + Enabled = table.Column(type: "bit", nullable: false), + ConsumerNodeIds = table.Column(type: "nvarchar(max)", nullable: false), + TargetMode = table.Column(type: "int", nullable: false), + Consistency = table.Column(type: "int", nullable: false), + ExpectedClusterId = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + ExpectedNodeId = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: true), + EligibleTargetNodeIds = table.Column(type: "nvarchar(max)", nullable: false), + Endpoints = table.Column(type: "nvarchar(max)", nullable: false), + SecretReference = table.Column(type: "nvarchar(512)", maxLength: 512, nullable: false), + SecretScopeClusterId = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + AllowedOperations = table.Column(type: "int", nullable: false), + TimeoutMilliseconds = table.Column(type: "int", nullable: false), + MaxBatchItems = table.Column(type: "int", nullable: false), + MaxPageItems = table.Column(type: "int", nullable: false), + MaxMessageBytes = table.Column(type: "int", nullable: false), + MaxStreams = table.Column(type: "int", nullable: false), + MaxMonitoredItems = table.Column(type: "int", nullable: false), + MaxPendingBytes = table.Column(type: "bigint", nullable: false), + RowVersion = table.Column(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(type: "uniqueidentifier", nullable: false, defaultValueSql: "NEWSEQUENTIALID()"), + DataExportId = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: true), + ClusterId = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + Revision = table.Column(type: "bigint", nullable: false), + Enabled = table.Column(type: "bit", nullable: false), + Realm = table.Column(type: "int", nullable: false), + RootKind = table.Column(type: "nvarchar(32)", maxLength: 32, nullable: false), + RootEntityId = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + PrincipalId = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + AllowedOperations = table.Column(type: "int", nullable: false), + MaxBatchItems = table.Column(type: "int", nullable: false), + MaxPageItems = table.Column(type: "int", nullable: false), + MaxMonitoredItems = table.Column(type: "int", nullable: false), + MaxStreams = table.Column(type: "int", nullable: false), + RowVersion = table.Column(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(type: "uniqueidentifier", nullable: false, defaultValueSql: "NEWSEQUENTIALID()"), + RemoteNamespaceMappingId = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: true), + ClusterId = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + DataConnectionId = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + Revision = table.Column(type: "bigint", nullable: false), + Enabled = table.Column(type: "bit", nullable: false), + ConsumerNodeIds = table.Column(type: "nvarchar(max)", nullable: false), + Realm = table.Column(type: "int", nullable: false), + RemoteRealm = table.Column(type: "int", nullable: false), + LocalParentKind = table.Column(type: "nvarchar(32)", maxLength: 32, nullable: false), + LocalParentId = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + BranchName = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + RemoteRootEntityId = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + RemoteNamespaceUri = table.Column(type: "nvarchar(512)", maxLength: 512, nullable: false), + RemoteIdentifierKind = table.Column(type: "nvarchar(32)", maxLength: 32, nullable: false), + RemoteIdentifier = table.Column(type: "nvarchar(512)", maxLength: 512, nullable: false), + ExpectedValueKind = table.Column(type: "int", nullable: true), + ExpectedArrayElementKind = table.Column(type: "int", nullable: true), + AllowedOperations = table.Column(type: "int", nullable: false), + WriteThrough = table.Column(type: "bit", nullable: false), + MaxProjectionNodes = table.Column(type: "int", nullable: false), + MaxProjectionDepth = table.Column(type: "int", nullable: false), + MetadataLeaseMilliseconds = table.Column(type: "int", nullable: false), + StaleTimeoutMilliseconds = table.Column(type: "int", nullable: false), + SamplingIntervalMilliseconds = table.Column(type: "int", nullable: false), + PublishingIntervalMilliseconds = table.Column(type: "int", nullable: false), + RowVersion = table.Column(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"); + } + + /// + 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. + } + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs index ccb372d71..250a90d66 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs @@ -345,6 +345,184 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations }); }); + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection", b => + { + b.Property("DataConnectionRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowedOperations") + .HasColumnType("int"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Consistency") + .HasColumnType("int"); + + b.PrimitiveCollection("ConsumerNodeIds") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DataConnectionId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.PrimitiveCollection("EligibleTargetNodeIds") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.PrimitiveCollection("Endpoints") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ExpectedClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ExpectedNodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("MaxBatchItems") + .HasColumnType("int"); + + b.Property("MaxMessageBytes") + .HasColumnType("int"); + + b.Property("MaxMonitoredItems") + .HasColumnType("int"); + + b.Property("MaxPageItems") + .HasColumnType("int"); + + b.Property("MaxPendingBytes") + .HasColumnType("bigint"); + + b.Property("MaxStreams") + .HasColumnType("int"); + + b.Property("Revision") + .HasColumnType("bigint"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SecretReference") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("SecretScopeClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("TargetMode") + .HasColumnType("int"); + + b.Property("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("DataExportRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowedOperations") + .HasColumnType("int"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DataExportId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("MaxBatchItems") + .HasColumnType("int"); + + b.Property("MaxMonitoredItems") + .HasColumnType("int"); + + b.Property("MaxPageItems") + .HasColumnType("int"); + + b.Property("MaxStreams") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Realm") + .HasColumnType("int"); + + b.Property("Revision") + .HasColumnType("bigint"); + + b.Property("RootEntityId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RootKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("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("DeploymentId") @@ -795,8 +973,8 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations b.Property("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("RemoteNamespaceMappingRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowedOperations") + .HasColumnType("int"); + + b.Property("BranchName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.PrimitiveCollection("ConsumerNodeIds") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DataConnectionId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("ExpectedArrayElementKind") + .HasColumnType("int"); + + b.Property("ExpectedValueKind") + .HasColumnType("int"); + + b.Property("LocalParentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("LocalParentKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("MaxProjectionDepth") + .HasColumnType("int"); + + b.Property("MaxProjectionNodes") + .HasColumnType("int"); + + b.Property("MetadataLeaseMilliseconds") + .HasColumnType("int"); + + b.Property("PublishingIntervalMilliseconds") + .HasColumnType("int"); + + b.Property("Realm") + .HasColumnType("int"); + + b.Property("RemoteIdentifier") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RemoteIdentifierKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("RemoteNamespaceMappingId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RemoteNamespaceUri") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RemoteRealm") + .HasColumnType("int"); + + b.Property("RemoteRootEntityId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Revision") + .HasColumnType("bigint"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SamplingIntervalMilliseconds") + .HasColumnType("int"); + + b.Property("StaleTimeoutMilliseconds") + .HasColumnType("int"); + + b.Property("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("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") diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs index c45161e41..fb69502c0 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs @@ -12,6 +12,10 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration; public sealed class OtOpcUaConfigDbContext(DbContextOptions options) : DbContext(options), IDataProtectionKeyContext { + public DbSet DataConnections => Set(); + public DbSet DataExports => Set(); + public DbSet RemoteNamespaceMappings => Set(); + /// Gets the DbSet of server clusters. public DbSet ServerClusters => Set(); /// Gets the DbSet of cluster nodes. @@ -73,6 +77,7 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions(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().WithMany().HasForeignKey(x => x.ClusterId).OnDelete(DeleteBehavior.Restrict); + }); + modelBuilder.Entity(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().WithMany().HasForeignKey(x => x.ClusterId).OnDelete(DeleteBehavior.Restrict); + }); + modelBuilder.Entity(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().WithMany().HasForeignKey(x => x.ClusterId).OnDelete(DeleteBehavior.Restrict); + }); + } + private static void ConfigureServerCluster(ModelBuilder modelBuilder) { modelBuilder.Entity(e => @@ -477,7 +538,7 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions x.NodeAclId).HasMaxLength(64); e.Property(x => x.ClusterId).HasMaxLength(64); e.Property(x => x.Principal).HasMaxLength(256); - e.Property(x => x.ScopeKind).HasConversion().HasMaxLength(16); + e.Property(x => x.ScopeKind).HasConversion().HasMaxLength(32); e.Property(x => x.ScopeId).HasMaxLength(64); e.Property(x => x.PermissionFlags).HasConversion(); e.Property(x => x.Notes).HasMaxLength(512); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs new file mode 100644 index 000000000..257955def --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs @@ -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; + +/// Validates deployed data-service configuration without resolving consumer-side secrets. +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 Validate(DraftSnapshot draft) + { + ArgumentNullException.ThrowIfNull(draft); + var errors = new List(); + 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 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 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(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; + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshot.cs index fd7dc35a7..8c105d157 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshot.cs @@ -74,6 +74,11 @@ public sealed class DraftSnapshot /// public IReadOnlyList ServerClusters { get; init; } = []; + /// Directional data connections, exports and mappings from the same consistent snapshot. + public IReadOnlyList DataConnections { get; init; } = []; + public IReadOnlyList DataExports { get; init; } = []; + public IReadOnlyList RemoteNamespaceMappings { get; init; } = []; + /// Cluster-node rows; see for why they ride the snapshot. public IReadOnlyList ClusterNodes { get; init; } = []; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs index 30873aca6..b864032df 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs @@ -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). diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs index a4e958e56..78eb0aa9f 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs @@ -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 => diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/ConfigComposer.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/ConfigComposer.cs index 39735ddb4..5bed779f3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/ConfigComposer.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/ConfigComposer.cs @@ -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(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(JsonSerializer.SerializeToUtf8Bytes(mapping, JsonOptions), JsonOptions)!; + copy.ConsumerNodeIds = copy.ConsumerNodeIds.OrderBy(x => x, StringComparer.Ordinal).ToList(); + return copy; + }).ToArray(), }; return Pack(JsonSerializer.SerializeToUtf8Bytes(ordered, JsonOptions)); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs new file mode 100644 index 000000000..603fe32a9 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs @@ -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 +{ + /// Read the node-effective data connections from an artifact. + public static IReadOnlyList ParseDataConnections( + ReadOnlySpan blob, + string nodeId + ) + { + using var parsed = Open(blob.ToArray()); + return parsed.ParseDataConnections(nodeId); + } + + /// Read the node-effective data exports from an artifact. + public static IReadOnlyList ParseDataExports(ReadOnlySpan blob, string nodeId) + { + using var parsed = Open(blob.ToArray()); + return parsed.ParseDataExports(nodeId); + } + + /// Read the node-effective remote namespace mappings from an artifact. + public static IReadOnlyList ParseRemoteNamespaceMappings( + ReadOnlySpan 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 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 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 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( + root, + "DataConnections", + "DataConnectionId", + clusterId + ); + var exports = ReadDataRows(root, "DataExports", "DataExportId", clusterId); + var mappings = ReadDataRows( + 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(root, "Clusters"), + ClusterNodes = ReadTopology(root, "Nodes"), + RawFolders = ReadTopology(root, "RawFolders"), + DriverInstances = ReadTopology(root, "DriverInstances"), + Devices = ReadTopology(root, "Devices"), + TagGroups = ReadTopology(root, "TagGroups"), + Tags = ReadTopology(root, "Tags"), + UnsAreas = ReadTopology(root, "UnsAreas"), + UnsLines = ReadTopology(root, "UnsLines"), + Equipment = ReadTopology(root, "Equipment"), + UnsTagReferences = ReadTopology(root, "UnsTagReferences"), + VirtualTags = ReadTopology(root, "VirtualTags"), + ScriptedAlarms = ReadTopology(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(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) ? "" : id)}'." + ); + + private static List ReadDataRows( + 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(); + 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(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 ReadTopology(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>(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 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); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.cs index 40cb890c5..57fc94b2a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.cs @@ -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. /// -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. /// /// -internal sealed class ParsedDeploymentArtifact : IDisposable +internal sealed partial class ParsedDeploymentArtifact : IDisposable { private readonly JsonDocument _document; diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataConfigurationTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataConfigurationTests.cs new file mode 100644 index 000000000..e0474f0b7 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataConfigurationTests.cs @@ -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); + } + +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataMappingValidationTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataMappingValidationTests.cs new file mode 100644 index 000000000..0d5721464 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataMappingValidationTests.cs @@ -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"); + } + +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataSchemaModelTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataSchemaModelTests.cs new file mode 100644 index 000000000..19fbcde88 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataSchemaModelTests.cs @@ -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() + .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().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() + .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(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DataConnections/GrpcDataArtifactProjectionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DataConnections/GrpcDataArtifactProjectionTests.cs new file mode 100644 index 000000000..4ff9780bd --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DataConnections/GrpcDataArtifactProjectionTests.cs @@ -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() + .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(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs new file mode 100644 index 000000000..eb7837c7e --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs @@ -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(() => 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(() => + 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(() => 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(() => + 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(() => parsed.ParseDataConnections(NodeA)); + + error.Message.ShouldContain("connection-a"); + error.Message.ShouldNotContain(presentedSecret); + } + + [Fact] + public void New_projections_are_materialized_and_survive_document_disposal() + { + IReadOnlyList connections; + IReadOnlyList exports; + IReadOnlyList 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(() => + 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(() => 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(() => 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(() => + { + if (collection == "DataConnections") + parsed.ParseDataConnections(NodeA); + else if (collection == "DataExports") + parsed.ParseDataExports(NodeA); + else + parsed.ParseRemoteNamespaceMappings(NodeA); + }); + error.Message.ShouldContain(""); + } + + [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(() => parsed.ParseDataConnections(NodeA)) + .Message.ShouldContain(""); + } + + [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(() => 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(() => 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(() => 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(); +}