fix(config): #998 deploy gate rejects duplicate ZTag/SAPID, duplicate owned historian tagnames and dangling parent links; NULL-keyed unique indexes enforced; node/cluster edits carry a RowVersion

C-3 ZTag/SAPID uniqueness enforced from the draft (reservation ledger has no writer); UI/doc claim corrected.
C-5 HistorianTagnameDuplicate (owned tags, per cluster, case-insensitive; readOnly exempt).
C-8 UX_NodeAcl_PrincipalScope / UX_LdapGroupRoleMapping_Group_Cluster unfiltered (migration with duplicate pre-check) + friendly service/page checks.
C-9 RowVersion on ClusterNode/ServerCluster, edit pages use it; node delete removes its NodeDeploymentState rows.
C-10 DanglingReference rule; dead PathTooLong/EquipmentUuidImmutable rules + PriorEquipment/Enterprise/Site inputs deleted.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-03 10:49:57 -05:00
parent b9955f6946
commit 486628cf0a
24 changed files with 2833 additions and 171 deletions
@@ -103,6 +103,12 @@ public sealed class ClusterNode
/// <summary>Gets or sets the username of who created this node.</summary>
public required string CreatedBy { get; set; }
/// <summary>
/// Optimistic-concurrency token (#998, review C-9). <see cref="Enabled"/> / <see cref="MaintenanceMode"/> define a
/// deploy's expected-ack set, so a stale edit form must not silently overwrite a concurrent change.
/// </summary>
public byte[] RowVersion { get; set; } = Array.Empty<byte>();
// Navigation
/// <summary>Gets or sets the cluster this node belongs to.</summary>
public ServerCluster? Cluster { get; set; }
@@ -32,10 +32,10 @@ public sealed class Equipment
/// <summary>Operator colloquial id (e.g. "machine_001"). Unique within cluster. Required.</summary>
public required string MachineCode { get; set; }
/// <summary>ERP equipment id. Unique fleet-wide via <see cref="ExternalIdReservation"/>. Primary browse identifier in Admin UI.</summary>
/// <summary>ERP equipment id. Unique fleet-wide, enforced by the deploy gate (<c>DraftValidator</c>, <c>BadDuplicateExternalIdentifier</c>; #998). Primary browse identifier in Admin UI.</summary>
public string? ZTag { get; set; }
/// <summary>SAP PM equipment id. Unique fleet-wide via <see cref="ExternalIdReservation"/>.</summary>
/// <summary>SAP PM equipment id. Unique fleet-wide, enforced by the deploy gate (<c>DraftValidator</c>; #998).</summary>
public string? SAPID { get; set; }
// OPC UA Companion Spec OPC 40010 Machinery Identification fields.
@@ -44,6 +44,9 @@ public sealed class ServerCluster
/// <summary>Gets or sets the user who last modified the cluster.</summary>
public string? ModifiedBy { get; set; }
/// <summary>Optimistic-concurrency token (#998, review C-9): a stale cluster edit form must not silently overwrite a concurrent change.</summary>
public byte[] RowVersion { get; set; } = Array.Empty<byte>();
// Navigation
/// <summary>Gets or sets the collection of cluster nodes.</summary>
public ICollection<ClusterNode> Nodes { get; set; } = [];
@@ -0,0 +1,98 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
{
/// <summary>
/// lmxopcua#998 (review C-8, C-9). C-8: <c>UX_NodeAcl_PrincipalScope</c> and
/// <c>UX_LdapGroupRoleMapping_Group_Cluster</c> were created with EF's implicit <c>WHERE [col] IS NOT NULL</c>
/// 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: <c>RowVersion</c> concurrency tokens on <c>ServerCluster</c> and <c>ClusterNode</c>.
/// </summary>
public partial class ConfigurationGapsIndexesAndRowVersions : Migration
{
/// <inheritdoc />
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<byte[]>(
name: "RowVersion",
table: "ServerCluster",
type: "rowversion",
rowVersion: true,
nullable: false,
defaultValue: new byte[0]);
migrationBuilder.AddColumn<byte[]>(
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);
}
/// <inheritdoc />
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");
}
}
}
@@ -156,6 +156,12 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
b.Property<int>("OpcUaPort")
.HasColumnType("int");
b.Property<byte[]>("RowVersion")
.IsConcurrencyToken()
.IsRequired()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("rowversion");
b.Property<byte>("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<byte[]>("RowVersion")
.IsConcurrencyToken()
.IsRequired()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("rowversion");
b.Property<string>("Site")
.IsRequired()
.HasMaxLength(32)
@@ -192,6 +192,7 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
e.Property(x => 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<OtOpcUaConfigDbConte
e.Property(x => 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<OtOpcUaConfigDbConte
.HasFilter("[ScopeId] IS NOT NULL")
.HasDatabaseName("IX_NodeAcl_Scope");
e.HasIndex(x => 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<OtOpcUaConfigDbConte
.HasForeignKey(x => 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
@@ -59,6 +59,18 @@ public sealed class LdapGroupRoleMappingService(IDbContextFactory<OtOpcUaConfigD
if (row.CreatedAtUtc == default) row.CreatedAtUtc = DateTime.UtcNow;
await using var db = await dbFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
// #998 (review C-8): one row per (LdapGroup, ClusterId); a NULL ClusterId (system-wide) is its own bucket.
// UX_LdapGroupRoleMapping_Group_Cluster enforces it, but say it in words instead of a raw DbUpdateException.
var duplicate = await db.LdapGroupRoleMappings
.AnyAsync(m => 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;
@@ -15,18 +15,6 @@ public sealed class DraftSnapshot
/// <summary>Gets the cluster identifier.</summary>
public required string ClusterId { get; init; }
/// <summary>
/// Cluster's Enterprise segment (UNS level 1). When set, <see cref="DraftValidator"/> uses
/// the actual length for path-length checks instead of a conservative 32-char upper bound.
/// </summary>
public string? Enterprise { get; init; }
/// <summary>
/// Cluster's Site segment (UNS level 2). When set, <see cref="DraftValidator"/> uses the
/// actual length for path-length checks instead of a conservative 32-char upper bound.
/// </summary>
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
/// </summary>
public IReadOnlyList<ApiKey> ApiKeys { get; init; } = [];
/// <summary>Prior Equipment rows (any generation, same cluster) for stability checks.</summary>
public IReadOnlyList<Equipment> PriorEquipment { get; init; } = [];
/// <summary>Active reservations (<c>ReleasedAt IS NULL</c>) for pre-flight.</summary>
public IReadOnlyList<ExternalIdReservation> ActiveReservations { get; init; } = [];
}
@@ -17,10 +17,9 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation;
/// </para>
/// <para>
/// <see cref="DraftSnapshot.GenerationId"/> is a placeholder (the generation model was
/// dropped); no rule reads it. <see cref="DraftSnapshot.PriorEquipment"/> is empty because
/// there is no prior-generation table to diff against. <see cref="DraftSnapshot.Enterprise"/>
/// / <see cref="DraftSnapshot.Site"/> are left null so the path-length rule uses its
/// conservative upper bound.
/// dropped); no rule reads it. (The prior-generation / path-length inputs
/// <c>PriorEquipment</c>, <c>Enterprise</c> and <c>Site</c> were removed with their never-firing rules,
/// lmxopcua#998 review C-10.)
/// </para>
/// <para>
/// <b>One consistent read.</b> 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
@@ -16,8 +16,6 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation;
/// </summary>
public static class DraftValidator
{
private const int MaxPathLength = 200;
/// <summary>
/// Validates a draft snapshot and returns all validation errors found in a single pass.
/// </summary>
@@ -28,8 +26,8 @@ public static class DraftValidator
var errors = new List<ValidationError>();
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));
}
/// <summary>Cluster.Enterprise + Site + area + line + equipment + 4 slashes ≤ 200 chars.</summary>
private static void ValidatePathLength(DraftSnapshot draft, List<ValidationError> errors)
/// <summary>The <c>DanglingReference</c> error code (lmxopcua#998, review C-10).</summary>
public const string DanglingReferenceCode = "DanglingReference";
/// <summary>The <c>HistorianTagnameDuplicate</c> error code (lmxopcua#998, review C-5).</summary>
public const string HistorianTagnameDuplicateCode = "HistorianTagnameDuplicate";
/// <summary>The ZTag / SAPID duplicate error code (decision #124's name, now raised from the draft itself).</summary>
public const string DuplicateExternalIdentifierCode = "BadDuplicateExternalIdentifier";
/// <summary>
/// lmxopcua#998 (review C-10): the parent links of the config tables are LOGICAL foreign keys only (no DB FK —
/// see <c>OtOpcUaConfigDbContext</c>), 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.
/// </summary>
private static void ValidateDanglingReferences(DraftSnapshot draft, List<ValidationError> 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<string> Ids<T>(IEnumerable<T> rows, Func<T, string> 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<string> 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");
}
/// <summary>
/// lmxopcua#998 (review C-5): two OWNED historized tags must not resolve to the same effective historian
/// tagname (the <c>historianTagname</c> override, else the RawPath), compared case-insensitively — AVEVA
/// historian tagnames are. A copied override (a tag duplicated in <c>/raw</c> 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.
/// <para>Decisions: a <c>historianReadOnly</c> 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.</para>
/// </summary>
private static void ValidateHistorianTagnameUniqueness(DraftSnapshot draft, List<ValidationError> 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<ValidationError> errors)
/// <summary>
/// lmxopcua#998 (review C-3): <c>Equipment.ZTag</c> and <c>Equipment.SAPID</c> are unique fleet-wide. The
/// former writer of the reservation ledger (<c>sp_PublishGeneration</c>) is gone, so
/// <see cref="ValidateReservationPreflight"/> 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".
/// </summary>
private static void ValidateEquipmentExternalIdUniqueness(DraftSnapshot draft, List<ValidationError> 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<Equipment, string?> 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<ValidationError> errors)
@@ -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))
@@ -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; } = [];
}
}
@@ -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; } = [];
}
}
@@ -23,7 +23,7 @@ else
<h2 class="panel-head">@_rows.Count reservation@(_rows.Count == 1 ? "" : "s")</h2>
@if (_rows.Count == 0)
{
<div style="padding:1rem" class="text-muted">No reservations yet.</div>
<div style="padding:1rem" class="text-muted">No reservations. (Nothing writes this ledger any more: ZTag / SAPID uniqueness is enforced by the deploy gate.)</div>
}
else
{
@@ -117,11 +117,12 @@ else
<div class="col-md-6 mb-3">
<label class="form-label" for='@FieldId("eq-ztag")'>ZTag (ERP)</label>
<InputText id='@FieldId("eq-ztag")' aria-describedby='@FieldId("eq-ztag-hint")' @bind-Value="form.ZTag" class="form-control form-control-sm" />
<div id='@FieldId("eq-ztag-hint")' class="form-text">Unique fleet-wide via ExternalIdReservation.</div>
<div id='@FieldId("eq-ztag-hint")' class="form-text">Must be unique fleet-wide (case-insensitive); a duplicate is rejected when you deploy.</div>
</div>
<div class="col-md-6 mb-3">
<label class="form-label" for='@FieldId("eq-sap")'>SAPID</label>
<InputText id='@FieldId("eq-sap")' @bind-Value="form.SAPID" class="form-control form-control-sm" />
<div class="form-text">Must be unique fleet-wide (case-insensitive); a duplicate is rejected when you deploy.</div>
</div>
</div>
<div class="mb-3">