diff --git a/.claude/rules/historian.md b/.claude/rules/historian.md index 348c7c302..657aa80ed 100644 --- a/.claude/rules/historian.md +++ b/.claude/rules/historian.md @@ -152,6 +152,10 @@ historian tag OtOpcUa never provisions (`AddressSpaceApplier.IsOwnedHistorizedVa recorder); node-inert ⇒ surgical; not mirrored on UNS refs; a non-bool value is the deploy error `HistorianReadOnlyInvalid`. The default for an explicit `historianTagname` is still OWNED (overrides pin owned history across renames). `docs/Historian.md` §"Read-only bindings to existing historian tags (#899)". +**Duplicate tagnames (#998):** two OWNED historized tags in one cluster whose effective tagname (the `historianTagname` override, else +the RawPath; case-insensitive) is equal are the deploy error `HistorianTagnameDuplicate` (`DraftValidator.ValidateHistorianTagnameUniqueness`) — +else both streams record into ONE historian tag and HistoryRead interleaves two signals. `historianReadOnly` tags are exempt (never provisioned +or recorded, so several may read one historian tag); clusters are checked separately (they may front different historians). ### Gateway-side prerequisites diff --git a/docs/Raw.md b/docs/Raw.md index 43e7f297b..13c373c0d 100644 --- a/docs/Raw.md +++ b/docs/Raw.md @@ -144,6 +144,16 @@ removed (terminal Bad, then `RemoveVariableNode`, which severs the backing raw n inverse `Organizes` edge) **before** the equipment subtree, and the subtree removal severs the same edge for anything it reaches itself (archreview 03/P5 + 03/S20). +## Deploy-gate integrity rules (lmxopcua#998) + +The parent links of the config tables (Tag→Device/TagGroup, Device→DriverInstance, Equipment→UnsLine, reference→Tag/Equipment, ...) are +**logical** foreign keys only, and the service-layer "is it empty?" delete checks are not serialised against a concurrent add. The deploy gate +(`DraftValidator.ValidateDanglingReferences`) therefore names every orphan as `DanglingReference` instead of letting each composer silently skip a +row with no path. Also enforced at the gate: fleet-wide `Equipment.ZTag` / `SAPID` uniqueness (`BadDuplicateExternalIdentifier`; see +`docs/Reservations.md`) and duplicate owned historian tagnames (`HistorianTagnameDuplicate`, `.claude/rules/historian.md`). The never-firing +`PathTooLong` and `EquipmentUuidImmutable` rules were deleted (the UnsSegment charset already bounds the path at 164 chars; no prior-generation +table exists to diff). + ## The `Calculation` driver Signal-level calculated tags are ordinary raw tags bound to a `Calculation` driver diff --git a/docs/Reservations.md b/docs/Reservations.md index 0b48980b0..29e0eeb98 100644 --- a/docs/Reservations.md +++ b/docs/Reservations.md @@ -1,5 +1,16 @@ # External-ID Reservations +> **Status (lmxopcua#998, 2026-12): the reservation ledger has no writer.** `sp_PublishGeneration`, the only code +> that inserted `ExternalIdReservation` rows, was retired with the generation model (it now only `RAISERROR`s), so the +> table stays empty and the pre-flight below can only fire against rows an operator inserted by hand. **Fleet-wide +> ZTag / SAPID uniqueness is now enforced by the deploy gate itself**: `DraftValidator.ValidateEquipmentExternalIdUniqueness` +> groups every equipment row in the (whole-DB) draft snapshot by trimmed, case-insensitive ZTag and by SAPID and +> reports each duplicate as `BadDuplicateExternalIdentifier` naming the other equipment (same cluster or not). +> Blank values mean "no identifier". The permanent-claim semantics described below (a retired asset's id staying +> reserved) are **not** provided; the table, `/reservations` page and release procedure remain for any rows that +> already exist. The equipment page's field hint says "rejected when you deploy", matching this. A filtered unique +> index on `Equipment.ZTag` / `SAPID` was not added (needs a duplicate pre-clean migration); the gate is the authority. + The reservation subsystem guarantees that an asset's **external identifiers** — its `ZTag` and `SAPID` — belong to exactly one piece of equipment across the entire fleet, for all time. It is the mechanism that stops two pieces of diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/ClusterNode.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/ClusterNode.cs index 20653c20c..c7524489d 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/ClusterNode.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/ClusterNode.cs @@ -103,6 +103,12 @@ public sealed class ClusterNode /// Gets or sets the username of who created this node. public required string CreatedBy { get; set; } + /// + /// Optimistic-concurrency token (#998, review C-9). / define a + /// deploy's expected-ack set, so a stale edit form must not silently overwrite a concurrent change. + /// + public byte[] RowVersion { get; set; } = Array.Empty(); + // Navigation /// Gets or sets the cluster this node belongs to. public ServerCluster? Cluster { get; set; } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/Equipment.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/Equipment.cs index ce5371481..e6cb5c592 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/Equipment.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/Equipment.cs @@ -32,10 +32,10 @@ public sealed class Equipment /// Operator colloquial id (e.g. "machine_001"). Unique within cluster. Required. public required string MachineCode { get; set; } - /// ERP equipment id. Unique fleet-wide via . Primary browse identifier in Admin UI. + /// ERP equipment id. Unique fleet-wide, enforced by the deploy gate (DraftValidator, BadDuplicateExternalIdentifier; #998). Primary browse identifier in Admin UI. public string? ZTag { get; set; } - /// SAP PM equipment id. Unique fleet-wide via . + /// SAP PM equipment id. Unique fleet-wide, enforced by the deploy gate (DraftValidator; #998). public string? SAPID { get; set; } // OPC UA Companion Spec OPC 40010 Machinery Identification fields. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/ServerCluster.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/ServerCluster.cs index ffcc94b26..23dde1acd 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/ServerCluster.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/ServerCluster.cs @@ -44,6 +44,9 @@ public sealed class ServerCluster /// Gets or sets the user who last modified the cluster. public string? ModifiedBy { get; set; } + /// Optimistic-concurrency token (#998, review C-9): a stale cluster edit form must not silently overwrite a concurrent change. + public byte[] RowVersion { get; set; } = Array.Empty(); + // Navigation /// Gets or sets the collection of cluster nodes. public ICollection Nodes { get; set; } = []; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261203154217_ConfigurationGapsIndexesAndRowVersions.Designer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261203154217_ConfigurationGapsIndexesAndRowVersions.Designer.cs new file mode 100644 index 000000000..e459d81eb --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261203154217_ConfigurationGapsIndexesAndRowVersions.Designer.cs @@ -0,0 +1,2022 @@ +// +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("20261203154217_ConfigurationGapsIndexesAndRowVersions")] + partial class ConfigurationGapsIndexesAndRowVersions + { + /// + 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("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + 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("HistoryTimeoutMilliseconds") + .HasColumnType("int"); + + 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 AND [HistoryTimeoutMilliseconds] > 0"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnectionScopeState", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("Fingerprint") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScopeVersion") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.ToTable("DataConnectionScopeState", null, t => + { + t.HasCheckConstraint("CK_DataConnectionScopeState_Singleton", "[Id] = 1 AND [ScopeVersion] >= 0"); + }); + + b.HasData( + new + { + Id = 1, + ScopeVersion = 0L + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataExport", b => + { + b.Property("DataExportRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowGalaxyServiceAck") + .HasColumnType("bit"); + + 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("MaxConcurrentHistoryReads") + .HasColumnType("int"); + + b.Property("MaxConditions") + .HasColumnType("int"); + + b.Property("MaxHistoryResponseBytes") + .HasColumnType("int"); + + b.Property("MaxHistoryValuesPerPage") + .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 AND [MaxConcurrentHistoryReads] > 0 AND [MaxHistoryValuesPerPage] > 0 AND [MaxHistoryResponseBytes] > 0 AND [MaxConditions] > 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"); + + 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"); + + 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.Property("ConditionMethodTimeoutMilliseconds") + .HasColumnType("int"); + + b.Property("ConditionSnapshotTimeoutMilliseconds") + .HasColumnType("int"); + + b.Property("ConditionStaleTimeoutMilliseconds") + .HasColumnType("int"); + + 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("MaxConditions") + .HasColumnType("int"); + + b.Property("MaxHistoryAssemblyBytesPerRequest") + .HasColumnType("int"); + + 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 AND [MaxHistoryAssemblyBytesPerRequest] > 0 AND [MaxConditions] > 0 AND [ConditionStaleTimeoutMilliseconds] > 0 AND [ConditionMethodTimeoutMilliseconds] > 0 AND [ConditionSnapshotTimeoutMilliseconds] > 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("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + 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/20261203154217_ConfigurationGapsIndexesAndRowVersions.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261203154217_ConfigurationGapsIndexesAndRowVersions.cs new file mode 100644 index 000000000..d4c4828bc --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261203154217_ConfigurationGapsIndexesAndRowVersions.cs @@ -0,0 +1,98 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations +{ + /// + /// lmxopcua#998 (review C-8, C-9). C-8: UX_NodeAcl_PrincipalScope and + /// UX_LdapGroupRoleMapping_Group_Cluster were created with EF's implicit WHERE [col] IS NOT NULL + /// filter, so NULL-keyed rows (Cluster-kind ACLs, system-wide LDAP mappings) were unconstrained although the model + /// comment promised one row per key. Recreated unfiltered (SQL Server treats NULLs as equal in a unique index). + /// Rows that duplicated in the meantime would make the CREATE fail halfway, so a pre-check names them first. + /// C-9: RowVersion concurrency tokens on ServerCluster and ClusterNode. + /// + public partial class ConfigurationGapsIndexesAndRowVersions : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.Sql(@" +IF EXISTS (SELECT 1 FROM [NodeAcl] GROUP BY [ClusterId], [Principal], [ScopeKind], [ScopeId] HAVING COUNT(*) > 1) + THROW 50998, 'ConfigurationGapsIndexesAndRowVersions: duplicate NodeAcl rows exist for one (ClusterId, Principal, ScopeKind, ScopeId) - typically several Cluster-scope rows for one principal. Delete or merge the duplicates, then re-run.', 1; +IF EXISTS (SELECT 1 FROM [LdapGroupRoleMapping] GROUP BY [LdapGroup], [ClusterId] HAVING COUNT(*) > 1) + THROW 50998, 'ConfigurationGapsIndexesAndRowVersions: duplicate LdapGroupRoleMapping rows exist for one (LdapGroup, ClusterId) - typically several system-wide rows for one group. Delete or merge the duplicates, then re-run.', 1; +"); + + migrationBuilder.DropIndex( + name: "UX_NodeAcl_PrincipalScope", + table: "NodeAcl"); + + migrationBuilder.DropIndex( + name: "UX_LdapGroupRoleMapping_Group_Cluster", + table: "LdapGroupRoleMapping"); + + migrationBuilder.AddColumn( + name: "RowVersion", + table: "ServerCluster", + type: "rowversion", + rowVersion: true, + nullable: false, + defaultValue: new byte[0]); + + migrationBuilder.AddColumn( + name: "RowVersion", + table: "ClusterNode", + type: "rowversion", + rowVersion: true, + nullable: false, + defaultValue: new byte[0]); + + migrationBuilder.CreateIndex( + name: "UX_NodeAcl_PrincipalScope", + table: "NodeAcl", + columns: new[] { "ClusterId", "Principal", "ScopeKind", "ScopeId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "UX_LdapGroupRoleMapping_Group_Cluster", + table: "LdapGroupRoleMapping", + columns: new[] { "LdapGroup", "ClusterId" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "UX_NodeAcl_PrincipalScope", + table: "NodeAcl"); + + migrationBuilder.DropIndex( + name: "UX_LdapGroupRoleMapping_Group_Cluster", + table: "LdapGroupRoleMapping"); + + migrationBuilder.DropColumn( + name: "RowVersion", + table: "ServerCluster"); + + migrationBuilder.DropColumn( + name: "RowVersion", + table: "ClusterNode"); + + migrationBuilder.CreateIndex( + name: "UX_NodeAcl_PrincipalScope", + table: "NodeAcl", + columns: new[] { "ClusterId", "Principal", "ScopeKind", "ScopeId" }, + unique: true, + filter: "[ScopeId] IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "UX_LdapGroupRoleMapping_Group_Cluster", + table: "LdapGroupRoleMapping", + columns: new[] { "LdapGroup", "ClusterId" }, + unique: true, + filter: "[ClusterId] IS NOT NULL"); + } + } +} 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 50be4aff1..2e5fe4637 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs @@ -156,6 +156,12 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations b.Property("OpcUaPort") .HasColumnType("int"); + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + b.Property("ServiceLevelBase") .HasColumnType("tinyint"); @@ -978,8 +984,7 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations b.HasIndex("LdapGroup", "ClusterId") .IsUnique() - .HasDatabaseName("UX_LdapGroupRoleMapping_Group_Cluster") - .HasFilter("[ClusterId] IS NOT NULL"); + .HasDatabaseName("UX_LdapGroupRoleMapping_Group_Cluster"); b.ToTable("LdapGroupRoleMapping", (string)null); }); @@ -1046,8 +1051,7 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations b.HasIndex("ClusterId", "Principal", "ScopeKind", "ScopeId") .IsUnique() - .HasDatabaseName("UX_NodeAcl_PrincipalScope") - .HasFilter("[ScopeId] IS NOT NULL"); + .HasDatabaseName("UX_NodeAcl_PrincipalScope"); b.ToTable("NodeAcl", (string)null); }); @@ -1507,6 +1511,12 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations .HasMaxLength(16) .HasColumnType("nvarchar(16)"); + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + b.Property("Site") .IsRequired() .HasMaxLength(32) diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs index e2d0fd0c8..c0ccccd8b 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs @@ -192,6 +192,7 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions x.CreatedBy).HasMaxLength(128); e.Property(x => x.ModifiedAt).HasColumnType("datetime2(3)"); e.Property(x => x.ModifiedBy).HasMaxLength(128); + e.Property(x => x.RowVersion).IsRowVersion(); e.HasIndex(x => x.Name).IsUnique().HasDatabaseName("UX_ServerCluster_Name"); e.HasIndex(x => x.Site).HasDatabaseName("IX_ServerCluster_Site"); }); @@ -216,6 +217,7 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions x.LastSeenAt).HasColumnType("datetime2(3)"); e.Property(x => x.CreatedAt).HasColumnType("datetime2(3)").HasDefaultValueSql("SYSUTCDATETIME()"); e.Property(x => x.CreatedBy).HasMaxLength(128); + e.Property(x => x.RowVersion).IsRowVersion(); e.HasOne(x => x.Cluster).WithMany(c => c.Nodes) .HasForeignKey(x => x.ClusterId) @@ -560,7 +562,12 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions x.NodeAclId).IsUnique().HasDatabaseName("UX_NodeAcl_LogicalId"); + // #998 (review C-8): HasFilter(null) is explicit — without it the SQL Server provider adds + // `WHERE [ScopeId] IS NOT NULL` to a unique index over a nullable column, which would leave the + // Cluster-kind rows (the only kind with a NULL ScopeId) unconstrained. Unfiltered, SQL Server treats + // NULL as one value, so there is at most ONE Cluster-scope row per (cluster, principal). e.HasIndex(x => new { x.ClusterId, x.Principal, x.ScopeKind, x.ScopeId }).IsUnique() + .HasFilter(null) .HasDatabaseName("UX_NodeAcl_PrincipalScope"); }); } @@ -667,12 +674,14 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions x.ClusterId) .OnDelete(DeleteBehavior.Cascade); - // Uniqueness: one row per (LdapGroup, ClusterId). Null ClusterId is treated as its own - // "bucket" so a system-wide row coexists with cluster-scoped rows for the same group. - // SQL Server treats NULL as a distinct value in unique-index comparisons by default - // since 2008 SP1 onwards under the session setting we use — tested in SchemaCompliance. + // Uniqueness: one row per (LdapGroup, ClusterId). A NULL ClusterId (system-wide) is its own + // bucket: one system-wide row per group, coexisting with cluster-scoped rows for that group. + // #998 (review C-8): SQL Server treats NULLs as EQUAL in a unique index, but the provider adds + // `WHERE [ClusterId] IS NOT NULL` to a unique index over a nullable column unless the filter is + // set explicitly — which silently exempted exactly the system-wide rows. HasFilter(null) opts out. e.HasIndex(x => new { x.LdapGroup, x.ClusterId }) .IsUnique() + .HasFilter(null) .HasDatabaseName("UX_LdapGroupRoleMapping_Group_Cluster"); // Hot-path lookup during cookie auth: "what grants does this user's set of LDAP diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Services/LdapGroupRoleMappingService.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Services/LdapGroupRoleMappingService.cs index 58ef80816..f7b17d820 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Services/LdapGroupRoleMappingService.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Services/LdapGroupRoleMappingService.cs @@ -59,6 +59,18 @@ public sealed class LdapGroupRoleMappingService(IDbContextFactory m.LdapGroup == row.LdapGroup && m.ClusterId == row.ClusterId, cancellationToken) + .ConfigureAwait(false); + if (duplicate) + throw new InvalidLdapGroupRoleMappingException( + $"A mapping for group '{row.LdapGroup}' already exists for " + + (row.ClusterId is null ? "the whole fleet (system-wide)" : $"cluster '{row.ClusterId}'") + + "; delete or change that row instead of adding a second one."); + db.LdapGroupRoleMappings.Add(row); await db.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return row; 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 184cc0900..8ee088f67 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshot.cs @@ -15,18 +15,6 @@ public sealed class DraftSnapshot /// Gets the cluster identifier. public required string ClusterId { get; init; } - /// - /// Cluster's Enterprise segment (UNS level 1). When set, uses - /// the actual length for path-length checks instead of a conservative 32-char upper bound. - /// - public string? Enterprise { get; init; } - - /// - /// Cluster's Site segment (UNS level 2). When set, uses the - /// actual length for path-length checks instead of a conservative 32-char upper bound. - /// - public string? Site { get; init; } - // v3: the Namespace entity is retired (the two OPC UA namespaces are implicit). The Raw tree // (RawFolders → DriverInstances → Devices → TagGroups → Tags) + the UNS projection // (UnsTagReferences) feed the v3 validator rules (raw-name charset, historized-tagname length, UNS @@ -90,9 +78,6 @@ public sealed class DraftSnapshot /// public IReadOnlyList ApiKeys { get; init; } = []; - /// Prior Equipment rows (any generation, same cluster) for stability checks. - public IReadOnlyList PriorEquipment { get; init; } = []; - /// Active reservations (ReleasedAt IS NULL) for pre-flight. public IReadOnlyList ActiveReservations { 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 c975740ab..0faacaee7 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs @@ -17,10 +17,9 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation; /// /// /// is a placeholder (the generation model was -/// dropped); no rule reads it. is empty because -/// there is no prior-generation table to diff against. -/// / are left null so the path-length rule uses its -/// conservative upper bound. +/// dropped); no rule reads it. (The prior-generation / path-length inputs +/// PriorEquipment, Enterprise and Site were removed with their never-firing rules, +/// lmxopcua#998 review C-10.) /// /// /// One consistent read. On a relational provider the tables are read inside a @@ -97,7 +96,6 @@ public static class DraftSnapshotFactory PollGroups = await db.PollGroups.AsNoTracking().OrderBy(x => x.PollGroupId).ToListAsync(ct), NodeAcls = await db.NodeAcls.AsNoTracking().OrderBy(x => x.NodeAclId).ToListAsync(ct), ApiKeys = await db.ApiKeys.AsNoTracking().OrderBy(x => x.ApiKeyId).ToListAsync(ct), - PriorEquipment = [], // intentional: no prior-generation table to diff against at this level ActiveReservations = await db.ExternalIdReservations .AsNoTracking() .Where(r => r.ReleasedAt == null) // active only — matches DraftSnapshot.ActiveReservations semantics 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 22bc451d5..9f41ba6f1 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs @@ -16,8 +16,6 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation; /// public static class DraftValidator { - private const int MaxPathLength = 200; - /// /// Validates a draft snapshot and returns all validation errors found in a single pass. /// @@ -28,8 +26,8 @@ public static class DraftValidator var errors = new List(); ValidateUnsSegments(draft, errors); - ValidatePathLength(draft, errors); - ValidateEquipmentUuidImmutability(draft, errors); + ValidateDanglingReferences(draft, errors); + ValidateEquipmentExternalIdUniqueness(draft, errors); ValidateReservationPreflight(draft, errors); ValidateEquipmentIdDerivation(draft, errors); @@ -37,6 +35,7 @@ public static class DraftValidator // and ValidateGalaxyTagFullName (blob-as-identity gone) are replaced by: ValidateRawNameCharset(draft, errors); ValidateHistorizedTagnameLength(draft, errors); + ValidateHistorianTagnameUniqueness(draft, errors); ValidateHistorianReadOnly(draft, errors); ValidateUnsLeafNames(draft, errors); ValidateUnsEffectiveLeafUniqueness(draft, errors); @@ -453,7 +452,7 @@ public static class DraftValidator var graph = new DependencyGraph(); foreach (var (_, rawPath, scriptId) in calcTags) { - if (rawPath is null) continue; // broken chain — flagged by the charset rule; not a graph node + if (rawPath is null) continue; // broken chain — flagged by DanglingReference; not a graph node var source = scriptId is not null && scriptSourceById.TryGetValue(scriptId, out var src) ? src : null; var calcDeps = EquipmentScriptPaths.ExtractDependencyRefs(source) .Where(calcRawPaths.Contains) @@ -721,7 +720,7 @@ public static class DraftValidator var intent = TagConfigIntent.Parse(t.TagConfig); if (!intent.IsHistorized) continue; // Effective tagname = explicit override else the computed RawPath (null when the chain is broken — - // a separate rule/charset check flags that; nothing to length-check here). + // DanglingReference flags that; nothing to length-check here). var effective = intent.HistorianTagname ?? resolver.TryBuildTagPath(t.DeviceId, t.TagGroupId, t.Name); if (effective is null || effective.Length <= MaxHistorianTagname) continue; errors.Add(new("HistorianTagnameTooLong", @@ -949,45 +948,150 @@ public static class DraftValidator errors.Add(new("UnsSegmentInvalid", UnsSegment.Describe("Equipment.Name", e.Name), e.EquipmentId)); } - /// Cluster.Enterprise + Site + area + line + equipment + 4 slashes ≤ 200 chars. - private static void ValidatePathLength(DraftSnapshot draft, List errors) + /// The DanglingReference error code (lmxopcua#998, review C-10). + public const string DanglingReferenceCode = "DanglingReference"; + + /// The HistorianTagnameDuplicate error code (lmxopcua#998, review C-5). + public const string HistorianTagnameDuplicateCode = "HistorianTagnameDuplicate"; + + /// The ZTag / SAPID duplicate error code (decision #124's name, now raised from the draft itself). + public const string DuplicateExternalIdentifierCode = "BadDuplicateExternalIdentifier"; + + /// + /// lmxopcua#998 (review C-10): the parent links of the config tables are LOGICAL foreign keys only (no DB FK — + /// see OtOpcUaConfigDbContext), and the service-layer "is it empty?" checks before a delete are not + /// serialised against a concurrent add. User A deleting an empty Device while user B adds a Tag under it + /// therefore commits both, leaving a row with no RawPath that every rule and every composer silently skips. + /// This rule is the single authority that names such orphans at the deploy gate: + /// Tag→Device, Tag→TagGroup, TagGroup→Device / parent TagGroup, Device→DriverInstance, + /// DriverInstance→RawFolder, RawFolder→parent RawFolder, UnsLine→UnsArea, Equipment→UnsLine, + /// UnsTagReference→Tag / Equipment, VirtualTag / ScriptedAlarm→Equipment. + /// + private static void ValidateDanglingReferences(DraftSnapshot draft, List errors) { - // Use actual Enterprise/Site lengths when the snapshot carries them (populated by - // DraftValidationService from the ServerCluster row). Fall back to a conservative - // 32-char upper bound per segment when not supplied — over-penalises short values - // but never under-penalises long ones, which is acceptable for the fallback case. - var enterpriseLen = draft.Enterprise?.Length ?? 32; - var siteLen = draft.Site?.Length ?? 32; + HashSet Ids(IEnumerable rows, Func id) => + rows.Select(id).ToHashSet(StringComparer.Ordinal); - var areaById = draft.UnsAreas.ToDictionary(a => a.UnsAreaId); - var lineById = draft.UnsLines.ToDictionary(l => l.UnsLineId); + var folders = Ids(draft.RawFolders, f => f.RawFolderId); + var drivers = Ids(draft.DriverInstances, d => d.DriverInstanceId); + var devices = Ids(draft.Devices, d => d.DeviceId); + var groups = Ids(draft.TagGroups, g => g.TagGroupId); + var tags = Ids(draft.Tags, t => t.TagId); + var areas = Ids(draft.UnsAreas, a => a.UnsAreaId); + var lines = Ids(draft.UnsLines, l => l.UnsLineId); + var equipment = Ids(draft.Equipment, e => e.EquipmentId); - foreach (var eq in draft.Equipment.Where(e => e.UnsLineId is not null)) + void Check(HashSet parents, string? parentId, string kind, string id, string parentKind) { - if (!lineById.TryGetValue(eq.UnsLineId!, out var line)) continue; - if (!areaById.TryGetValue(line.UnsAreaId, out var area)) continue; + if (string.IsNullOrEmpty(parentId) || parents.Contains(parentId)) return; + errors.Add(new(DanglingReferenceCode, + $"{kind} '{id}' references {parentKind} '{parentId}', which does not exist (deleted concurrently?) — " + + $"the {kind} has no path and would be skipped by the deploy; delete or re-parent it", + id)); + } - var len = enterpriseLen + siteLen + area.Name.Length + line.Name.Length + eq.Name.Length + 4; - if (len > MaxPathLength) - errors.Add(new("PathTooLong", - $"Equipment path exceeds {MaxPathLength} chars (approx {len})", - eq.EquipmentId)); + foreach (var f in draft.RawFolders) Check(folders, f.ParentRawFolderId, "RawFolder", f.RawFolderId, "parent RawFolder"); + foreach (var d in draft.DriverInstances) Check(folders, d.RawFolderId, "DriverInstance", d.DriverInstanceId, "RawFolder"); + foreach (var d in draft.Devices) Check(drivers, d.DriverInstanceId, "Device", d.DeviceId, "DriverInstance"); + foreach (var g in draft.TagGroups) + { + Check(devices, g.DeviceId, "TagGroup", g.TagGroupId, "Device"); + Check(groups, g.ParentTagGroupId, "TagGroup", g.TagGroupId, "parent TagGroup"); + } + foreach (var t in draft.Tags) + { + Check(devices, t.DeviceId, "Tag", t.TagId, "Device"); + Check(groups, t.TagGroupId, "Tag", t.TagId, "TagGroup"); + } + foreach (var l in draft.UnsLines) Check(areas, l.UnsAreaId, "UnsLine", l.UnsLineId, "UnsArea"); + foreach (var e in draft.Equipment) Check(lines, e.UnsLineId, "Equipment", e.EquipmentId, "UnsLine"); + foreach (var r in draft.UnsTagReferences) + { + Check(tags, r.TagId, "UnsTagReference", r.UnsTagReferenceId, "Tag"); + Check(equipment, r.EquipmentId, "UnsTagReference", r.UnsTagReferenceId, "Equipment"); + } + foreach (var v in draft.VirtualTags) Check(equipment, v.EquipmentId, "VirtualTag", v.VirtualTagId, "Equipment"); + foreach (var a in draft.ScriptedAlarms) Check(equipment, a.EquipmentId, "ScriptedAlarm", a.ScriptedAlarmId, "Equipment"); + } + + /// + /// lmxopcua#998 (review C-5): two OWNED historized tags must not resolve to the same effective historian + /// tagname (the historianTagname override, else the RawPath), compared case-insensitively — AVEVA + /// historian tagnames are. A copied override (a tag duplicated in /raw or CSV-imported from a template) + /// would otherwise provision ONE historian tag and record both signals into it, so HistoryRead through either + /// NodeId returns the interleaved values of two different signals. + /// Decisions: a historianReadOnly tag is exempt — OtOpcUa neither provisions nor records into it, + /// so several read-only bindings (or a read-only alias of an owned tag) legitimately read the same historian + /// tag. The check is scoped per cluster: RawPaths are only unique within a cluster and clusters may front + /// different historians, so a cross-cluster name match is not provably a collision. + /// + private static void ValidateHistorianTagnameUniqueness(DraftSnapshot draft, List errors) + { + var resolver = BuildRawPathResolver(draft); + var clusterByDriver = draft.DriverInstances.GroupBy(d => d.DriverInstanceId, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.First().ClusterId, StringComparer.Ordinal); + var clusterByDevice = draft.Devices.GroupBy(d => d.DeviceId, StringComparer.Ordinal) + .ToDictionary( + g => g.Key, + g => clusterByDriver.TryGetValue(g.First().DriverInstanceId, out var c) ? c : string.Empty, + StringComparer.Ordinal); + + var owners = new List<(string Cluster, string Tagname, string TagId)>(); + foreach (var t in draft.Tags) + { + var intent = TagConfigIntent.Parse(t.TagConfig); + if (!intent.IsHistorized || intent.HistorianReadOnly) continue; + var effective = intent.HistorianTagname ?? resolver.TryBuildTagPath(t.DeviceId, t.TagGroupId, t.Name); + if (string.IsNullOrWhiteSpace(effective)) continue; + clusterByDevice.TryGetValue(t.DeviceId, out var cluster); + owners.Add((cluster ?? string.Empty, effective, t.TagId)); + } + + foreach (var g in owners.GroupBy(o => (o.Cluster, Name: o.Tagname.ToUpperInvariant()))) + { + var members = g.ToList(); + if (members.Count < 2) continue; + foreach (var m in members) + { + var others = string.Join(", ", members.Where(o => o.TagId != m.TagId).Select(o => $"'{o.TagId}'")); + errors.Add(new(HistorianTagnameDuplicateCode, + $"tag '{m.TagId}' historian tagname '{m.Tagname}' is also the effective tagname of {others}; " + + "both would be recorded into one historian tag. Give one a distinct 'historianTagname' override, " + + "or mark the others 'historianReadOnly'", + m.TagId)); + } } } - private static void ValidateEquipmentUuidImmutability(DraftSnapshot draft, List errors) + /// + /// lmxopcua#998 (review C-3): Equipment.ZTag and Equipment.SAPID are unique fleet-wide. The + /// former writer of the reservation ledger (sp_PublishGeneration) is gone, so + /// alone enforced nothing; the draft snapshot is the whole config + /// DB (every cluster), so the duplicate check is done here, on the draft, which IS the authority. + /// Compared trimmed and case-insensitively (the DB collation is); blank values mean "no identifier". + /// + private static void ValidateEquipmentExternalIdUniqueness(DraftSnapshot draft, List errors) { - var priorById = draft.PriorEquipment - .GroupBy(e => e.EquipmentId) - .ToDictionary(g => g.Key, g => g.First().EquipmentUuid); - - foreach (var eq in draft.Equipment) + void Check(string label, Func selector) { - if (priorById.TryGetValue(eq.EquipmentId, out var priorUuid) && priorUuid != eq.EquipmentUuid) - errors.Add(new("EquipmentUuidImmutable", - $"EquipmentId '{eq.EquipmentId}' had UUID '{priorUuid}' in a prior generation; cannot change to '{eq.EquipmentUuid}'", - eq.EquipmentId)); + foreach (var g in draft.Equipment + .Where(e => !string.IsNullOrWhiteSpace(selector(e))) + .GroupBy(e => selector(e)!.Trim(), StringComparer.OrdinalIgnoreCase)) + { + var members = g.ToList(); + if (members.Count < 2) continue; + foreach (var e in members) + { + var others = string.Join(", ", members.Where(o => o.EquipmentId != e.EquipmentId).Select(o => $"'{o.EquipmentId}'")); + errors.Add(new(DuplicateExternalIdentifierCode, + $"{label} '{selector(e)!.Trim()}' of equipment '{e.EquipmentId}' is also set on {others}; a {label} must be unique fleet-wide", + e.EquipmentId)); + } + } } + + Check("ZTag", e => e.ZTag); + Check("SAPID", e => e.SAPID); } private static void ValidateReservationPreflight(DraftSnapshot draft, List errors) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/AclEdit.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/AclEdit.razor index d7b2c5e74..22ac502b1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/AclEdit.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/AclEdit.razor @@ -252,6 +252,15 @@ else if (!_scope.Ok) { _error = $"Scope: {_scope.Message}"; return; } await using var db = await DbFactory.CreateDbContextAsync(); + + // #998 (review C-8): UX_NodeAcl_PrincipalScope allows one row per (cluster, principal, scope kind, + // scope id) — including one Cluster-scope row (NULL scope id). Report it in words. + var scopeId = string.IsNullOrWhiteSpace(_form.ScopeId) ? null : _form.ScopeId; + var editedId = IsNew ? _form.NodeAclId : NodeAclId; + if (await db.NodeAcls.AnyAsync(a => a.ClusterId == ClusterId && a.Principal == _form.Principal + && a.ScopeKind == _form.ScopeKind && a.ScopeId == scopeId && a.NodeAclId != editedId)) + { _error = $"An ACL for '{_form.Principal}' at this scope already exists in this cluster; edit that row instead."; return; } + if (IsNew) { if (await db.NodeAcls.AnyAsync(a => a.NodeAclId == _form.NodeAclId)) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterEdit.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterEdit.razor index 5a93eef62..559819d0e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterEdit.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterEdit.razor @@ -139,6 +139,7 @@ else RedundancyMode = _existing.RedundancyMode, Enabled = _existing.Enabled, Notes = _existing.Notes, + RowVersion = _existing.RowVersion, }; } _loaded = true; @@ -154,6 +155,8 @@ else var entity = await db.ServerClusters.FirstOrDefaultAsync(c => c.ClusterId == ClusterId); if (entity is null) { _error = "Cluster no longer exists."; return; } + // #998 (review C-9): the token loaded with the form, so a stale form cannot overwrite a concurrent edit. + db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion; var auth = await AuthState.GetAuthenticationStateAsync(); entity.Name = _form.Name; entity.Enterprise = _form.Enterprise; @@ -168,6 +171,10 @@ else await db.SaveChangesAsync(); Nav.NavigateTo($"/clusters/{ClusterId}"); } + catch (DbUpdateConcurrencyException) + { + _error = "Another user changed this cluster while you were editing. Reload the page and re-apply your change."; + } catch (Exception ex) { _error = ex.Message; @@ -209,5 +216,6 @@ else public RedundancyMode RedundancyMode { get; set; } = RedundancyMode.None; public bool Enabled { get; set; } = true; public string? Notes { get; set; } + public byte[] RowVersion { get; set; } = []; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/NodeEdit.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/NodeEdit.razor index 818a7c5f9..c5b965e5d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/NodeEdit.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/NodeEdit.razor @@ -177,6 +177,7 @@ else ServiceLevelBase = _existing.ServiceLevelBase, Enabled = _existing.Enabled, DriverConfigOverridesJson = _existing.DriverConfigOverridesJson, + RowVersion = _existing.RowVersion, }; } } @@ -251,6 +252,9 @@ else var entity = await db.ClusterNodes.FirstOrDefaultAsync( n => n.ClusterId == ClusterId && n.NodeId == NodeId); if (entity is null) { _error = "Row no longer exists."; return; } + // #998 (review C-9): the token loaded with the form, not the one just re-read — otherwise a + // concurrent edit (e.g. Enabled flipped for maintenance) would be silently overwritten. + db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion; entity.Host = _form.Host; entity.OpcUaPort = _form.OpcUaPort; entity.DashboardPort = _form.DashboardPort; @@ -262,6 +266,10 @@ else await db.SaveChangesAsync(); Nav.NavigateTo($"/clusters/{ClusterId}"); } + catch (DbUpdateConcurrencyException) + { + _error = "Another user changed this node while you were editing. Reload the page and re-apply your change."; + } catch (Exception ex) { _error = ex.Message; @@ -283,6 +291,10 @@ else var entity = await db.ClusterNodes.FirstOrDefaultAsync( n => n.ClusterId == ClusterId && n.NodeId == NodeId); if (entity is null) { Nav.NavigateTo($"/clusters/{ClusterId}"); return; } + // #998 (review C-9): NodeDeploymentState.NodeId is a Restrict FK, so a node that was ever deployed + // to could not be deleted (raw FK error). Its per-deployment ack rows are history about THIS node + // and meaningless without it: remove them in the same transaction. + db.NodeDeploymentStates.RemoveRange(await db.NodeDeploymentStates.Where(s => s.NodeId == NodeId).ToListAsync()); db.ClusterNodes.Remove(entity); await db.SaveChangesAsync(); Nav.NavigateTo($"/clusters/{ClusterId}"); @@ -321,5 +333,6 @@ else [Range(0, 255)] public int ServiceLevelBase { get; set; } = 200; public bool Enabled { get; set; } = true; public string? DriverConfigOverridesJson { get; set; } + public byte[] RowVersion { get; set; } = []; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Reservations.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Reservations.razor index aae435988..3d4bb24b5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Reservations.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Reservations.razor @@ -23,7 +23,7 @@ else

@_rows.Count reservation@(_rows.Count == 1 ? "" : "s")

@if (_rows.Count == 0) { -
No reservations yet.
+
No reservations. (Nothing writes this ledger any more: ZTag / SAPID uniqueness is enforced by the deploy gate.)
} else { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Uns/EquipmentPage.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Uns/EquipmentPage.razor index 5237c2aed..a0864bf05 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Uns/EquipmentPage.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Uns/EquipmentPage.razor @@ -117,11 +117,12 @@ else
-
Unique fleet-wide via ExternalIdReservation.
+
Must be unique fleet-wide (case-insensitive); a duplicate is rejected when you deploy.
+
Must be unique fleet-wide (case-insensitive); a duplicate is rejected when you deploy.
diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/ConfigurationGapsSchemaTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/ConfigurationGapsSchemaTests.cs new file mode 100644 index 000000000..24decad4d --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/ConfigurationGapsSchemaTests.cs @@ -0,0 +1,174 @@ +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; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests; + +/// +/// lmxopcua#998 (review 2026-12-02 03-configuration C-8, C-9) against the real SQL schema: the two unique +/// indexes over nullable columns must cover the NULL-key rows, and ClusterNode / ServerCluster carry a +/// concurrency token. +/// +[Trait("Category", "SchemaCompliance")] +[Collection(nameof(SchemaComplianceCollection))] +public sealed class ConfigurationGapsSchemaTests +{ + private readonly SchemaComplianceFixture _fixture; + + /// Initializes a new instance of the class. + /// The schema compliance fixture (real SQL DB). + public ConfigurationGapsSchemaTests(SchemaComplianceFixture fixture) => _fixture = fixture; + + private OtOpcUaConfigDbContext NewContext() => + new(new DbContextOptionsBuilder().UseSqlServer(_fixture.ConnectionString).Options); + + private static string Id(string prefix) => $"{prefix}-{Guid.NewGuid():N}"; + + private string SeedCluster() + { + var clusterId = Id("cl"); + using var db = NewContext(); + db.ServerClusters.Add(new ServerCluster + { + ClusterId = clusterId, Name = Id("Cluster"), Enterprise = "zb", Site = "dev", NodeCount = 1, + RedundancyMode = RedundancyMode.None, CreatedBy = "t998", + }); + db.SaveChanges(); + return clusterId; + } + + private static NodeAcl ClusterAcl(string clusterId, string principal) => new() + { + NodeAclId = Id("acl"), ClusterId = clusterId, Principal = principal, + ScopeKind = NodeAclScopeKind.Cluster, ScopeId = null, PermissionFlags = NodePermissions.Browse, + }; + + /// The recorded index definitions are unfiltered (HasFilter(null)) — the model comment's "one row per key" holds for NULLs too. + [Fact] + public void The_two_nullable_unique_indexes_are_not_filtered() + { + using var db = NewContext(); + var filtered = db.Database.SqlQueryRaw( + "SELECT name AS Value FROM sys.indexes WHERE is_unique = 1 AND has_filter = 1 " + + "AND name IN ('UX_NodeAcl_PrincipalScope', 'UX_LdapGroupRoleMapping_Group_Cluster')").ToList(); + + filtered.ShouldBeEmpty(); + } + + /// Two system-wide mappings for one group (NULL ClusterId) now collide. + [Fact] + public void Two_system_wide_mappings_for_one_group_are_rejected() + { + var group = Id("cn=grp"); + using var db = NewContext(); + db.LdapGroupRoleMappings.Add(new LdapGroupRoleMapping { LdapGroup = group, Role = AdminRole.Administrator, IsSystemWide = true }); + db.LdapGroupRoleMappings.Add(new LdapGroupRoleMapping { LdapGroup = group, Role = AdminRole.Designer, IsSystemWide = true }); + + Should.Throw(() => db.SaveChanges()); + } + + /// Positive control: a system-wide row plus a cluster row, and one row for another group, are all fine. + [Fact] + public void System_wide_plus_cluster_scoped_and_other_groups_are_accepted() + { + var group = Id("cn=grp"); + var cluster = SeedCluster(); + using var db = NewContext(); + db.LdapGroupRoleMappings.Add(new LdapGroupRoleMapping { LdapGroup = group, Role = AdminRole.Administrator, IsSystemWide = true }); + db.LdapGroupRoleMappings.Add(new LdapGroupRoleMapping { LdapGroup = group, Role = AdminRole.Designer, ClusterId = cluster, IsSystemWide = false }); + db.LdapGroupRoleMappings.Add(new LdapGroupRoleMapping { LdapGroup = Id("cn=other"), Role = AdminRole.Administrator, IsSystemWide = true }); + + Should.NotThrow(() => db.SaveChanges()); + } + + /// Two Cluster-scope ACL rows (NULL ScopeId) for one principal in one cluster now collide. + [Fact] + public void Two_cluster_scope_acls_for_one_principal_are_rejected() + { + var cluster = SeedCluster(); + using var db = NewContext(); + db.NodeAcls.Add(ClusterAcl(cluster, "grp-a")); + db.NodeAcls.Add(ClusterAcl(cluster, "grp-a")); + + Should.Throw(() => db.SaveChanges()); + } + + /// Positive control: other principal, and the same principal in another cluster, are fine. + [Fact] + public void Cluster_scope_acls_for_other_principals_or_clusters_are_accepted() + { + var a = SeedCluster(); + var b = SeedCluster(); + using var db = NewContext(); + db.NodeAcls.Add(ClusterAcl(a, "grp-a")); + db.NodeAcls.Add(ClusterAcl(a, "grp-b")); + db.NodeAcls.Add(ClusterAcl(b, "grp-a")); + + Should.NotThrow(() => db.SaveChanges()); + } + + /// A stale ClusterNode write (token loaded before a concurrent edit) is refused, not last-writer-wins. + [Fact] + public void A_stale_cluster_node_edit_is_refused() + { + var cluster = SeedCluster(); + var nodeId = Id("node") + ":4053"; + using (var seed = NewContext()) + { + seed.ClusterNodes.Add(new ClusterNode + { + NodeId = nodeId, ClusterId = cluster, Host = "h", ApplicationUri = "urn:" + Id("n"), CreatedBy = "t998", + }); + seed.SaveChanges(); + } + + byte[] staleToken; + using (var form = NewContext()) staleToken = form.ClusterNodes.AsNoTracking().Single(n => n.NodeId == nodeId).RowVersion; + staleToken.ShouldNotBeEmpty(); + + using (var other = NewContext()) + { + var n = other.ClusterNodes.Single(x => x.NodeId == nodeId); + n.Enabled = false; + other.SaveChanges(); + } + + using var stale = NewContext(); + var entity = stale.ClusterNodes.Single(x => x.NodeId == nodeId); + stale.Entry(entity).Property(e => e.RowVersion).OriginalValue = staleToken; + entity.Host = "changed"; + Should.Throw(() => stale.SaveChanges()); + } + + /// The same for ServerCluster; positive control: a write with the CURRENT token succeeds. + [Fact] + public void A_stale_server_cluster_edit_is_refused_but_a_current_one_succeeds() + { + var cluster = SeedCluster(); + byte[] staleToken; + using (var form = NewContext()) staleToken = form.ServerClusters.AsNoTracking().Single(c => c.ClusterId == cluster).RowVersion; + + using (var other = NewContext()) + { + other.ServerClusters.Single(c => c.ClusterId == cluster).Notes = "concurrent"; + other.SaveChanges(); + } + + using (var stale = NewContext()) + { + var entity = stale.ServerClusters.Single(c => c.ClusterId == cluster); + stale.Entry(entity).Property(e => e.RowVersion).OriginalValue = staleToken; + entity.Notes = "stale"; + Should.Throw(() => stale.SaveChanges()); + } + + using var current = NewContext(); + var fresh = current.ServerClusters.Single(c => c.ClusterId == cluster); + current.Entry(fresh).Property(e => e.RowVersion).OriginalValue = fresh.RowVersion; + fresh.Notes = "current"; + Should.NotThrow(() => current.SaveChanges()); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorConfigurationGapsTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorConfigurationGapsTests.cs new file mode 100644 index 000000000..aadd25c64 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorConfigurationGapsTests.cs @@ -0,0 +1,241 @@ +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; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests; + +/// +/// lmxopcua#998 (review 2026-12-02 03-configuration C-3, C-5, C-10) — the deploy-gate rules that make the +/// draft the one authority: ZTag/SAPID duplicates, duplicate historian tagnames, and dangling logical FKs. +/// +[Trait("Category", "Unit")] +public sealed class DraftValidatorConfigurationGapsTests +{ + private static DriverInstance Driver(string id = "drv-1", string cluster = "c1") => new() + { + DriverInstanceId = id, ClusterId = cluster, Name = "drv-" + id, DriverType = "Modbus", DriverConfig = "{}", + }; + + private static Device Dev(string id = "dev-1", string driver = "drv-1") => new() + { + DeviceId = id, DriverInstanceId = driver, Name = "dev-" + id, DeviceConfig = "{}", + }; + + private static Tag HistTag(string id, string name, string? tagname = null, bool readOnly = false, + string device = "dev-1", bool historized = true) + { + var cfg = new List(); + if (historized) cfg.Add("\"isHistorized\":true"); + if (tagname is not null) cfg.Add($"\"historianTagname\":\"{tagname}\""); + if (readOnly) cfg.Add("\"historianReadOnly\":true"); + return new Tag + { + TagId = id, DeviceId = device, Name = name, DataType = "Float", + AccessLevel = TagAccessLevel.Read, TagConfig = "{" + string.Join(",", cfg) + "}", + }; + } + + private static Guid UuidOf(string key) => new(System.Security.Cryptography.MD5.HashData(System.Text.Encoding.UTF8.GetBytes(key))); + + /// The canonical (derived) EquipmentId for ; the validator rejects any other id. + private static string Id(string key) => DraftValidator.DeriveEquipmentId(UuidOf(key)); + + private static Equipment Eq(string key, string? ztag = null, string? sap = null) => new() + { + EquipmentUuid = UuidOf(key), EquipmentId = Id(key), Name = "eq-" + key.ToLowerInvariant(), UnsLineId = "line-1", + MachineCode = "m-" + key, ZTag = ztag, SAPID = sap, + }; + + private static DraftSnapshot Snap( + IReadOnlyList? tags = null, IReadOnlyList? equipment = null, + IReadOnlyList? drivers = null, IReadOnlyList? devices = null) => new() + { + GenerationId = 1, ClusterId = "c1", + UnsAreas = [new UnsArea { UnsAreaId = "area-1", ClusterId = "c1", Name = "area" }], + UnsLines = [new UnsLine { UnsLineId = "line-1", UnsAreaId = "area-1", Name = "line" }], + DriverInstances = drivers ?? [Driver()], + Devices = devices ?? [Dev()], + Tags = tags ?? [], + Equipment = equipment ?? [], + }; + + // ----- C-3: ZTag / SAPID uniqueness ----- + + /// Two equipment rows with the same ZTag (no reservation rows at all, as in production) are both named. + [Fact] + public void Duplicate_ztag_is_rejected_without_any_reservation_rows() + { + var errors = DraftValidator.Validate(Snap(equipment: [Eq("a", ztag: "ZT-001"), Eq("b", ztag: "zt-001 ")])); + + var dup = errors.Where(e => e.Code == DraftValidator.DuplicateExternalIdentifierCode).ToList(); + dup.Count.ShouldBe(2); + dup.Select(e => e.Context).ShouldBe([Id("a"), Id("b")], ignoreOrder: true); + dup[0].Message.ShouldContain("ZTag"); + } + + /// The same rule covers SAPID. + [Fact] + public void Duplicate_sapid_is_rejected() + { + var errors = DraftValidator.Validate(Snap(equipment: [Eq("a", sap: "S1"), Eq("b", sap: "S1")])); + + errors.Count(e => e.Code == DraftValidator.DuplicateExternalIdentifierCode).ShouldBe(2); + } + + /// Positive control: distinct values, repeated nulls and blanks, and a ZTag equal to another row's SAPID are all fine. + [Fact] + public void Distinct_null_and_blank_external_ids_are_accepted() + { + var errors = DraftValidator.Validate(Snap(equipment: + [ + Eq("a", ztag: "ZT-1", sap: "X"), Eq("b", ztag: "ZT-2", sap: "Y"), + Eq("c"), Eq("d"), Eq("e", ztag: " ", sap: ""), Eq("f", ztag: "", sap: " "), + Eq("g", ztag: "X"), + ])); + + errors.ShouldNotContain(e => e.Code == DraftValidator.DuplicateExternalIdentifierCode); + } + + // ----- C-5: historian tagname duplicates ----- + + /// A copied override: two owned historized tags with the same override are both named. + [Fact] + public void Two_owned_tags_with_the_same_historian_override_are_rejected() + { + var errors = DraftValidator.Validate(Snap(tags: + [ + HistTag("t1", "speed", "Plant.Speed"), HistTag("t2", "speed2", "plant.speed"), + ])); + + var dup = errors.Where(e => e.Code == DraftValidator.HistorianTagnameDuplicateCode).ToList(); + dup.Select(e => e.Context).ShouldBe(["t1", "t2"], ignoreOrder: true); + } + + /// An override equal to another tag's computed RawPath is the same collision. + [Fact] + public void An_override_equal_to_another_tags_rawpath_is_rejected() + { + // t1's RawPath = drv-drv-1/dev-dev-1/speed (no RawFolder); t2 overrides to exactly that. + var errors = DraftValidator.Validate(Snap(tags: + [ + HistTag("t1", "speed"), HistTag("t2", "other", "drv-drv-1/dev-dev-1/speed"), + ])); + + errors.Count(e => e.Code == DraftValidator.HistorianTagnameDuplicateCode).ShouldBe(2); + } + + /// Positive controls: distinct names, a non-historized twin, and a historianReadOnly twin (decision: read-only sharing allowed). + [Fact] + public void Distinct_non_historized_and_read_only_twins_are_accepted() + { + var errors = DraftValidator.Validate(Snap(tags: + [ + HistTag("t1", "a", "Plant.A"), HistTag("t2", "b", "Plant.B"), + HistTag("t3", "c", "Plant.A", historized: false), + HistTag("t4", "d", "Plant.A", readOnly: true), + HistTag("t5", "e", "Plant.RO", readOnly: true), HistTag("t6", "f", "Plant.RO", readOnly: true), + ])); + + errors.ShouldNotContain(e => e.Code == DraftValidator.HistorianTagnameDuplicateCode); + } + + /// The same override in two clusters is not provably a collision (separate historians): accepted. + [Fact] + public void The_same_override_in_different_clusters_is_accepted() + { + var errors = DraftValidator.Validate(Snap( + drivers: [Driver("drv-1", "c1"), Driver("drv-2", "c2")], + devices: [Dev("dev-1", "drv-1"), Dev("dev-2", "drv-2")], + tags: [HistTag("t1", "a", "Plant.A"), HistTag("t2", "a", "Plant.A", device: "dev-2")])); + + errors.ShouldNotContain(e => e.Code == DraftValidator.HistorianTagnameDuplicateCode); + } + + // ----- C-10: dangling references ----- + + /// The orphan scenario: a tag whose Device was deleted concurrently is named, not silently skipped. + [Fact] + public void A_tag_under_a_deleted_device_is_rejected() + { + var errors = DraftValidator.Validate(Snap(tags: [HistTag("t1", "a", historized: false, device: "dev-gone")])); + + var e = errors.ShouldHaveSingleItem(); + e.Code.ShouldBe(DraftValidator.DanglingReferenceCode); + e.Context.ShouldBe("t1"); + e.Message.ShouldContain("dev-gone"); + } + + /// Positive control: a complete, consistent graph (every link present) produces no error at all. + [Fact] + public void A_consistent_graph_has_no_dangling_reference() + { + var errors = DraftValidator.Validate(Snap( + tags: [HistTag("t1", "a", historized: false)], + equipment: [Eq("a")])); + + errors.ShouldBeEmpty(); + } + + /// One case per logical link. + [Theory] + [InlineData("tag-group")] + [InlineData("tag-device")] + [InlineData("taggroup-device")] + [InlineData("taggroup-parent")] + [InlineData("device-driver")] + [InlineData("driver-folder")] + [InlineData("folder-parent")] + [InlineData("line-area")] + [InlineData("equipment-line")] + [InlineData("ref-tag")] + [InlineData("ref-equipment")] + [InlineData("vtag-equipment")] + [InlineData("alarm-equipment")] + public void Every_logical_parent_link_is_checked(string link) + { + var tag = HistTag("t1", "a", historized: false); + var snap = link switch + { + "tag-group" => Snap(tags: [Mutate(tag, t => t.TagGroupId = "g-gone")]), + "tag-device" => Snap(tags: [Mutate(tag, t => t.DeviceId = "dev-gone")]), + "taggroup-device" => With(Snap(tags: [tag]), tagGroups: [new TagGroup { TagGroupId = "g1", DeviceId = "dev-gone", Name = "g" }]), + "taggroup-parent" => With(Snap(tags: [tag]), tagGroups: [new TagGroup { TagGroupId = "g1", DeviceId = "dev-1", ParentTagGroupId = "g-gone", Name = "g" }]), + "device-driver" => Snap(tags: [tag], devices: [Dev("dev-1", "drv-gone")]), + "driver-folder" => Snap(tags: [tag], drivers: [Mutate(Driver(), d => d.RawFolderId = "f-gone")]), + "folder-parent" => With(Snap(tags: [tag]), rawFolders: [new RawFolder { RawFolderId = "f1", ClusterId = "c1", ParentRawFolderId = "f-gone", Name = "f" }]), + "line-area" => Snap(tags: [tag]), + "equipment-line" => Snap(tags: [tag], equipment: [Mutate(Eq("a"), e => e.UnsLineId = "line-gone")]), + "ref-tag" => With(Snap(tags: [tag], equipment: [Eq("a")]), refs: [new UnsTagReference { UnsTagReferenceId = "r1", EquipmentId = Id("a"), TagId = "t-gone" }]), + "ref-equipment" => With(Snap(tags: [tag], equipment: [Eq("a")]), refs: [new UnsTagReference { UnsTagReferenceId = "r1", EquipmentId = "EQ-gone", TagId = "t1" }]), + "vtag-equipment" => With(Snap(tags: [tag]), vtags: [new VirtualTag { VirtualTagId = "v1", EquipmentId = "EQ-gone", Name = "v", DataType = "Double", ScriptId = "s1", ChangeTriggered = true }], scripts: [Script("s1")]), + "alarm-equipment" => With(Snap(tags: [tag]), alarms: [new ScriptedAlarm { ScriptedAlarmId = "a1", EquipmentId = "EQ-gone", Name = "al", AlarmType = "LimitAlarm", MessageTemplate = "m", PredicateScriptId = "s1" }], scripts: [Script("s1")]), + _ => throw new ArgumentOutOfRangeException(nameof(link)), + }; + if (link == "line-area") + snap = new DraftSnapshot + { + GenerationId = 1, ClusterId = "c1", UnsLines = [new UnsLine { UnsLineId = "line-1", UnsAreaId = "area-gone", Name = "line" }], + }; + + var errors = DraftValidator.Validate(snap).Where(e => e.Code == DraftValidator.DanglingReferenceCode).ToList(); + + errors.ShouldHaveSingleItem(); + } + + private static T Mutate(T row, Action change) { change(row); return row; } + + private static Script Script(string id) => new() { ScriptId = id, Name = id, SourceCode = "return 1;", SourceHash = "h" }; + + private static DraftSnapshot With(DraftSnapshot s, IReadOnlyList? tagGroups = null, IReadOnlyList? rawFolders = null, + IReadOnlyList? refs = null, IReadOnlyList? vtags = null, + IReadOnlyList? alarms = null, IReadOnlyList