fix(config): #1040 #1049 script FKs, unique ZTag/SAPID indexes, reservation ledger retired

One migration, ScriptForeignKeysAndExternalIdUniqueness:
- FK_VirtualTag_Script / FK_ScriptedAlarm_Script (Restrict) onto Script.ScriptId, which becomes
  NOT NULL and an alternate key (unique constraint UX_Script_LogicalId replaces the index).
- UX_Equipment_ZTag / UX_Equipment_SAPID filtered UNIQUE indexes (blank = no identifier, the
  deploy gate's reading) replace the non-unique IX_ ones.
- ExternalIdReservation + sp_ReleaseExternalIdReservation dropped (decision: retire — no writer
  since the generation model; uniqueness is gate + indexes). The /reservations page, query,
  ReservationKind, DraftSnapshot.ActiveReservations and the reservation pre-flight rule go too.
- A read-only pre-check THROWs 51049 naming every offending row class (NULL ScriptId, dangling
  VirtualTag/ScriptedAlarm script, duplicated ZTag/SAPID, any reservation row) and changes
  nothing; Down restores the previous shape.

Authoring mirrors so the constraints are never the first to say no: UnsTreeService refuses a
missing script for VirtualTag/ScriptedAlarm create/update, and a ZTag/SAPID another equipment
holds on create/update/import (owner named; import keeps the clean rows); values stored trimmed.
ScriptEdit maps a concurrent-bind FK refusal to a message. Migration pre-check, Down round-trip,
FK and index behaviour pinned against real SQL with positive controls.
This commit is contained in:
Joseph Doherty
2026-12-03 15:14:26 -05:00
parent 682ab34137
commit 90de55535d
34 changed files with 3002 additions and 624 deletions
@@ -1,44 +0,0 @@
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Entities;
/// <summary>
/// Fleet-wide rollback-safe reservation of ZTag and SAPID. NOT generation-versioned.
/// Exists outside generation flow specifically because old generations and disabled equipment can
/// still hold the same external IDs; per-generation uniqueness indexes fail under rollback/re-enable.
/// </summary>
public sealed class ExternalIdReservation
{
/// <summary>Gets or sets the unique reservation identifier.</summary>
public Guid ReservationId { get; set; }
/// <summary>Gets or sets the kind of reservation (ZTag or SAPID).</summary>
public required ReservationKind Kind { get; set; }
/// <summary>Gets or sets the reserved external ID value.</summary>
public required string Value { get; set; }
/// <summary>The equipment that owns this reservation. Stays bound even when equipment is disabled.</summary>
public Guid EquipmentUuid { get; set; }
/// <summary>First cluster to publish this reservation.</summary>
public required string ClusterId { get; set; }
/// <summary>Gets or sets the timestamp when the reservation was first published.</summary>
public DateTime FirstPublishedAt { get; set; } = DateTime.UtcNow;
/// <summary>Gets or sets the identifier of the user or system that first published the reservation.</summary>
public required string FirstPublishedBy { get; set; }
/// <summary>Gets or sets the timestamp of the most recent publication.</summary>
public DateTime LastPublishedAt { get; set; } = DateTime.UtcNow;
/// <summary>Non-null when explicitly released by FleetAdmin (audit-logged, requires reason).</summary>
public DateTime? ReleasedAt { get; set; }
/// <summary>Gets or sets the identifier of the user or system that released the reservation.</summary>
public string? ReleasedBy { get; set; }
/// <summary>Gets or sets the reason for releasing the reservation.</summary>
public string? ReleaseReason { get; set; }
}
@@ -1,8 +0,0 @@
namespace ZB.MOM.WW.OtOpcUa.Configuration.Enums;
/// <summary>External-ID reservation kind.</summary>
public enum ReservationKind
{
ZTag,
SAPID,
}
@@ -0,0 +1,267 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
{
/// <summary>
/// lmxopcua#1040 + lmxopcua#1049 (follow-ups of the 2026-12-02 review, #978 C-2 and #998 C-3).
/// <list type="bullet">
/// <item>Real FKs <c>FK_VirtualTag_Script</c> / <c>FK_ScriptedAlarm_Script</c> (ON DELETE NO ACTION) onto
/// <c>Script.ScriptId</c>, which becomes NOT NULL and an alternate key (the unique constraint
/// <c>UX_Script_LogicalId</c> replaces the filtered unique index of the same name).</item>
/// <item>Filtered UNIQUE indexes <c>UX_Equipment_ZTag</c> / <c>UX_Equipment_SAPID</c> (blank = no identifier,
/// as the deploy gate) replace the non-unique <c>IX_Equipment_ZTag</c> / <c>IX_Equipment_SAPID</c>.</item>
/// <item><c>ExternalIdReservation</c> and <c>sp_ReleaseExternalIdReservation</c> are dropped: the ledger has
/// had no writer since the generation model retired.</item>
/// </list>
/// <para><b>Pre-check, never a silent clean.</b> Each change would fail half-way (or delete history) over rows
/// that break it, so <see cref="PreCheckSql"/> runs first and THROWs one error naming every offending row class:
/// a NULL <c>Script.ScriptId</c>, a VirtualTag / ScriptedAlarm naming a missing script, a duplicated non-blank
/// ZTag or SAPID, and any <c>ExternalIdReservation</c> row. Nothing is altered until the operator fixes them; the
/// <c>preflight</c> tool (docs/v2/upgrade-preflight.md) lists the same rows ahead of the upgrade.</para>
/// </summary>
public partial class ScriptForeignKeysAndExternalIdUniqueness : Migration
{
/// <summary>The read-only pre-check; THROWs 51049 naming every problem class, or does nothing.</summary>
internal const string PreCheckSql = @"
DECLARE @problems nvarchar(max) = N'';
DECLARE @n int, @sample nvarchar(max);
SELECT @n = COUNT(*) FROM [Script] WHERE [ScriptId] IS NULL;
IF @n > 0 SET @problems += CONCAT(N' [', @n, N' Script row(s) with a NULL ScriptId: give each a unique ScriptId or delete it]');
SET @sample = N'';
SELECT @n = COUNT(*) FROM [VirtualTag] v WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.[ScriptId] = v.[ScriptId]);
SELECT TOP (5) @sample += CONCAT(N' ', v.[VirtualTagId], N'->', v.[ScriptId])
FROM [VirtualTag] v WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.[ScriptId] = v.[ScriptId]) ORDER BY v.[VirtualTagId];
IF @n > 0 SET @problems += CONCAT(N' [', @n, N' VirtualTag row(s) name a script that does not exist (VirtualTagId->ScriptId:', @sample, N'): point them at an existing script or delete them]');
SET @sample = N'';
SELECT @n = COUNT(*) FROM [ScriptedAlarm] a WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.[ScriptId] = a.[PredicateScriptId]);
SELECT TOP (5) @sample += CONCAT(N' ', a.[ScriptedAlarmId], N'->', a.[PredicateScriptId])
FROM [ScriptedAlarm] a WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.[ScriptId] = a.[PredicateScriptId]) ORDER BY a.[ScriptedAlarmId];
IF @n > 0 SET @problems += CONCAT(N' [', @n, N' ScriptedAlarm row(s) name a predicate script that does not exist (ScriptedAlarmId->PredicateScriptId:', @sample, N'): point them at an existing script or delete them]');
SET @sample = N'';
SELECT @n = COUNT(*) FROM (SELECT [ZTag] FROM [Equipment] WHERE [ZTag] IS NOT NULL AND [ZTag] <> N'' GROUP BY [ZTag] HAVING COUNT(*) > 1) d;
SELECT TOP (5) @sample += CONCAT(N' ''', d.[ZTag], N''' x', d.c)
FROM (SELECT [ZTag], COUNT(*) AS c FROM [Equipment] WHERE [ZTag] IS NOT NULL AND [ZTag] <> N'' GROUP BY [ZTag] HAVING COUNT(*) > 1) d ORDER BY d.[ZTag];
IF @n > 0 SET @problems += CONCAT(N' [', @n, N' ZTag value(s) are set on more than one Equipment row (', @sample, N'): keep each ZTag on one equipment and clear or change the others]');
SET @sample = N'';
SELECT @n = COUNT(*) FROM (SELECT [SAPID] FROM [Equipment] WHERE [SAPID] IS NOT NULL AND [SAPID] <> N'' GROUP BY [SAPID] HAVING COUNT(*) > 1) d;
SELECT TOP (5) @sample += CONCAT(N' ''', d.[SAPID], N''' x', d.c)
FROM (SELECT [SAPID], COUNT(*) AS c FROM [Equipment] WHERE [SAPID] IS NOT NULL AND [SAPID] <> N'' GROUP BY [SAPID] HAVING COUNT(*) > 1) d ORDER BY d.[SAPID];
IF @n > 0 SET @problems += CONCAT(N' [', @n, N' SAPID value(s) are set on more than one Equipment row (', @sample, N'): keep each SAPID on one equipment and clear or change the others]');
IF OBJECT_ID(N'[ExternalIdReservation]', N'U') IS NOT NULL
BEGIN
SELECT @n = COUNT(*) FROM [ExternalIdReservation];
IF @n > 0 SET @problems += CONCAT(N' [', @n, N' ExternalIdReservation row(s): the ledger is retired and its table is dropped by this migration; export the rows if you need their history, DELETE FROM [ExternalIdReservation], then re-run]');
END
IF LEN(@problems) > 0
BEGIN
DECLARE @msg nvarchar(2048) = LEFT(CONCAT(N'ScriptForeignKeysAndExternalIdUniqueness (lmxopcua#1040/#1049) refused - nothing was changed:', @problems), 2048);
THROW 51049, @msg, 1;
END
";
// sp_ReleaseExternalIdReservation as V3Initial created it — re-created by Down only.
private const string ReleaseExternalIdReservationProc = @"
CREATE OR ALTER PROCEDURE dbo.sp_ReleaseExternalIdReservation
@Kind nvarchar(16),
@Value nvarchar(64),
@ReleaseReason nvarchar(512)
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
IF @ReleaseReason IS NULL OR LEN(@ReleaseReason) = 0
BEGIN
RAISERROR('ReleaseReason is required', 16, 1);
RETURN;
END
UPDATE dbo.ExternalIdReservation
SET ReleasedAt = SYSUTCDATETIME(),
ReleasedBy = SUSER_SNAME(),
ReleaseReason = @ReleaseReason
WHERE Kind = @Kind AND Value = @Value AND ReleasedAt IS NULL;
IF @@ROWCOUNT = 0
BEGIN
RAISERROR('No active reservation found for (%s, %s)', 16, 1, @Kind, @Value);
RETURN;
END
INSERT dbo.ConfigAuditLog (Principal, EventType, DetailsJson)
VALUES (SUSER_SNAME(), 'ExternalIdReleased',
CONCAT('{""kind"":""', STRING_ESCAPE(@Kind, 'json'),
'"",""value"":""', STRING_ESCAPE(@Value, 'json'), '""}'));
END
";
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(PreCheckSql);
migrationBuilder.Sql("IF OBJECT_ID(N'dbo.sp_ReleaseExternalIdReservation', N'P') IS NOT NULL DROP PROCEDURE dbo.sp_ReleaseExternalIdReservation;");
migrationBuilder.DropTable(
name: "ExternalIdReservation");
migrationBuilder.DropIndex(
name: "UX_Script_LogicalId",
table: "Script");
migrationBuilder.DropIndex(
name: "IX_Equipment_SAPID",
table: "Equipment");
migrationBuilder.DropIndex(
name: "IX_Equipment_ZTag",
table: "Equipment");
migrationBuilder.AlterColumn<string>(
name: "ScriptId",
table: "Script",
type: "nvarchar(64)",
maxLength: 64,
nullable: false,
oldClrType: typeof(string),
oldType: "nvarchar(64)",
oldMaxLength: 64,
oldNullable: true);
migrationBuilder.AddUniqueConstraint(
name: "UX_Script_LogicalId",
table: "Script",
column: "ScriptId");
migrationBuilder.CreateIndex(
name: "UX_Equipment_SAPID",
table: "Equipment",
column: "SAPID",
unique: true,
filter: "[SAPID] IS NOT NULL AND [SAPID] <> N''");
migrationBuilder.CreateIndex(
name: "UX_Equipment_ZTag",
table: "Equipment",
column: "ZTag",
unique: true,
filter: "[ZTag] IS NOT NULL AND [ZTag] <> N''");
migrationBuilder.AddForeignKey(
name: "FK_ScriptedAlarm_Script",
table: "ScriptedAlarm",
column: "PredicateScriptId",
principalTable: "Script",
principalColumn: "ScriptId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_VirtualTag_Script",
table: "VirtualTag",
column: "ScriptId",
principalTable: "Script",
principalColumn: "ScriptId",
onDelete: ReferentialAction.Restrict);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_ScriptedAlarm_Script",
table: "ScriptedAlarm");
migrationBuilder.DropForeignKey(
name: "FK_VirtualTag_Script",
table: "VirtualTag");
migrationBuilder.DropUniqueConstraint(
name: "UX_Script_LogicalId",
table: "Script");
migrationBuilder.DropIndex(
name: "UX_Equipment_SAPID",
table: "Equipment");
migrationBuilder.DropIndex(
name: "UX_Equipment_ZTag",
table: "Equipment");
migrationBuilder.AlterColumn<string>(
name: "ScriptId",
table: "Script",
type: "nvarchar(64)",
maxLength: 64,
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(64)",
oldMaxLength: 64);
migrationBuilder.CreateTable(
name: "ExternalIdReservation",
columns: table => new
{
ReservationId = table.Column<Guid>(type: "uniqueidentifier", nullable: false, defaultValueSql: "NEWSEQUENTIALID()"),
ClusterId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false),
EquipmentUuid = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
FirstPublishedAt = table.Column<DateTime>(type: "datetime2(3)", nullable: false, defaultValueSql: "SYSUTCDATETIME()"),
FirstPublishedBy = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false),
Kind = table.Column<string>(type: "nvarchar(16)", maxLength: 16, nullable: false),
LastPublishedAt = table.Column<DateTime>(type: "datetime2(3)", nullable: false, defaultValueSql: "SYSUTCDATETIME()"),
ReleaseReason = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: true),
ReleasedAt = table.Column<DateTime>(type: "datetime2(3)", nullable: true),
ReleasedBy = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: true),
Value = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ExternalIdReservation", x => x.ReservationId);
});
migrationBuilder.CreateIndex(
name: "UX_Script_LogicalId",
table: "Script",
column: "ScriptId",
unique: true,
filter: "[ScriptId] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_Equipment_SAPID",
table: "Equipment",
column: "SAPID",
filter: "[SAPID] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_Equipment_ZTag",
table: "Equipment",
column: "ZTag",
filter: "[ZTag] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_ExternalIdReservation_Equipment",
table: "ExternalIdReservation",
column: "EquipmentUuid");
migrationBuilder.CreateIndex(
name: "UX_ExternalIdReservation_KindValue_Active",
table: "ExternalIdReservation",
columns: new[] { "Kind", "Value" },
unique: true,
filter: "[ReleasedAt] IS NULL");
migrationBuilder.Sql(ReleaseExternalIdReservationProc);
migrationBuilder.Sql(@"
IF DATABASE_PRINCIPAL_ID('OtOpcUaAdmin') IS NOT NULL
GRANT EXECUTE ON OBJECT::dbo.sp_ReleaseExternalIdReservation TO OtOpcUaAdmin;");
}
}
}
@@ -864,15 +864,17 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
.HasDatabaseName("IX_Equipment_MachineCode");
b.HasIndex("SAPID")
.HasDatabaseName("IX_Equipment_SAPID")
.HasFilter("[SAPID] IS NOT NULL");
.IsUnique()
.HasDatabaseName("UX_Equipment_SAPID")
.HasFilter("[SAPID] IS NOT NULL AND [SAPID] <> N''");
b.HasIndex("UnsLineId")
.HasDatabaseName("IX_Equipment_Line");
b.HasIndex("ZTag")
.HasDatabaseName("IX_Equipment_ZTag")
.HasFilter("[ZTag] IS NOT NULL");
.IsUnique()
.HasDatabaseName("UX_Equipment_ZTag")
.HasFilter("[ZTag] IS NOT NULL AND [ZTag] <> N''");
b.HasIndex("UnsLineId", "Name")
.IsUnique()
@@ -881,70 +883,6 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
b.ToTable("Equipment", (string)null);
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ExternalIdReservation", b =>
{
b.Property<Guid>("ReservationId")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier")
.HasDefaultValueSql("NEWSEQUENTIALID()");
b.Property<string>("ClusterId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<Guid>("EquipmentUuid")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("FirstPublishedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime2(3)")
.HasDefaultValueSql("SYSUTCDATETIME()");
b.Property<string>("FirstPublishedBy")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("nvarchar(16)");
b.Property<DateTime>("LastPublishedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime2(3)")
.HasDefaultValueSql("SYSUTCDATETIME()");
b.Property<string>("ReleaseReason")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<DateTime?>("ReleasedAt")
.HasColumnType("datetime2(3)");
b.Property<string>("ReleasedBy")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("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<Guid>("Id")
@@ -1362,6 +1300,7 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
.HasColumnType("rowversion");
b.Property<string>("ScriptId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
@@ -1376,10 +1315,8 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
b.HasKey("ScriptRowId");
b.HasIndex("ScriptId")
.IsUnique()
.HasDatabaseName("UX_Script_LogicalId")
.HasFilter("[ScriptId] IS NOT NULL");
b.HasAlternateKey("ScriptId")
.HasName("UX_Script_LogicalId");
b.HasIndex("SourceHash")
.HasDatabaseName("IX_Script_SourceHash");
@@ -1991,6 +1928,17 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
.IsRequired();
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ScriptedAlarm", b =>
{
b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Script", null)
.WithMany()
.HasForeignKey("PredicateScriptId")
.HasPrincipalKey("ScriptId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("FK_ScriptedAlarm_Script");
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsArea", b =>
{
b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster")
@@ -2002,6 +1950,17 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
b.Navigation("Cluster");
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.VirtualTag", b =>
{
b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Script", null)
.WithMany()
.HasForeignKey("ScriptId")
.HasPrincipalKey("ScriptId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("FK_VirtualTag_Script");
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", b =>
{
b.Navigation("Credentials");
@@ -50,8 +50,6 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
public DbSet<ApiKey> ApiKeys => Set<ApiKey>();
/// <summary>Gets the DbSet of configuration audit logs.</summary>
public DbSet<ConfigAuditLog> ConfigAuditLogs => Set<ConfigAuditLog>();
/// <summary>Gets the DbSet of external ID reservations.</summary>
public DbSet<ExternalIdReservation> ExternalIdReservations => Set<ExternalIdReservation>();
/// <summary>Gets the DbSet of LDAP group role mappings.</summary>
public DbSet<LdapGroupRoleMapping> LdapGroupRoleMappings => Set<LdapGroupRoleMapping>();
/// <summary>Gets the DbSet of scripts.</summary>
@@ -104,7 +102,6 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
ConfigureNodeAcl(modelBuilder);
ConfigureApiKey(modelBuilder);
ConfigureConfigAuditLog(modelBuilder);
ConfigureExternalIdReservation(modelBuilder);
ConfigureLdapGroupRoleMapping(modelBuilder);
ConfigureScript(modelBuilder);
ConfigureVirtualTag(modelBuilder);
@@ -454,8 +451,16 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
e.HasIndex(x => x.EquipmentId).IsUnique().HasDatabaseName("UX_Equipment_LogicalId");
e.HasIndex(x => new { x.UnsLineId, x.Name }).IsUnique().HasDatabaseName("UX_Equipment_LinePath");
e.HasIndex(x => x.EquipmentUuid).IsUnique().HasDatabaseName("UX_Equipment_Uuid");
e.HasIndex(x => x.ZTag).HasFilter("[ZTag] IS NOT NULL").HasDatabaseName("IX_Equipment_ZTag");
e.HasIndex(x => x.SAPID).HasFilter("[SAPID] IS NOT NULL").HasDatabaseName("IX_Equipment_SAPID");
// lmxopcua#1049 (#998 C-3 follow-up): ZTag and SAPID are unique fleet-wide. The deploy gate
// (DraftValidator.ValidateEquipmentExternalIdUniqueness, trimmed + case-insensitive, blank = none) stays
// the authority that names every duplicate; these filtered UNIQUE indexes are the storage backstop, so a
// concurrent save or a hand edit cannot persist a second claim. The filter matches the gate's "blank
// means no identifier" (SQL Server compares '' and ' ' equal, so both are exempt); the column
// collation is case-insensitive, as the gate is. ExternalIdReservation is retired (same issue).
e.HasIndex(x => x.ZTag).IsUnique()
.HasFilter("[ZTag] IS NOT NULL AND [ZTag] <> N''").HasDatabaseName("UX_Equipment_ZTag");
e.HasIndex(x => x.SAPID).IsUnique()
.HasFilter("[SAPID] IS NOT NULL AND [SAPID] <> N''").HasDatabaseName("UX_Equipment_SAPID");
e.HasIndex(x => x.MachineCode).HasDatabaseName("IX_Equipment_MachineCode");
});
}
@@ -612,34 +617,11 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
});
}
private static void ConfigureExternalIdReservation(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ExternalIdReservation>(e =>
{
e.ToTable("ExternalIdReservation");
e.HasKey(x => x.ReservationId);
e.Property(x => x.ReservationId).HasDefaultValueSql("NEWSEQUENTIALID()");
e.Property(x => x.Kind).HasConversion<string>().HasMaxLength(16);
e.Property(x => x.Value).HasMaxLength(64);
e.Property(x => x.ClusterId).HasMaxLength(64);
e.Property(x => x.FirstPublishedAt).HasColumnType("datetime2(3)").HasDefaultValueSql("SYSUTCDATETIME()");
e.Property(x => x.FirstPublishedBy).HasMaxLength(128);
e.Property(x => x.LastPublishedAt).HasColumnType("datetime2(3)").HasDefaultValueSql("SYSUTCDATETIME()");
e.Property(x => x.ReleasedAt).HasColumnType("datetime2(3)");
e.Property(x => x.ReleasedBy).HasMaxLength(128);
e.Property(x => x.ReleaseReason).HasMaxLength(512);
// Active reservations unique per (Kind, Value) — filtered index lets released rows coexist with a new reservation of the same value.
// The UX_ filtered index covers active-reservation lookups; history queries over released rows
// fall back to the table scan (released rows are rare + small). No separate non-unique (Kind, Value)
// index is declared because EF Core merges duplicate column sets into a single index, which would
// clobber the filtered-unique name.
e.HasIndex(x => new { x.Kind, x.Value }).IsUnique()
.HasFilter("[ReleasedAt] IS NULL")
.HasDatabaseName("UX_ExternalIdReservation_KindValue_Active");
e.HasIndex(x => x.EquipmentUuid).HasDatabaseName("IX_ExternalIdReservation_Equipment");
});
}
// ConfigureExternalIdReservation is GONE (lmxopcua#1049). The ledger's only writer was sp_PublishGeneration,
// retired with the generation model, so the table stayed empty and the reservation pre-flight could not fire.
// Fleet-wide ZTag / SAPID uniqueness is the deploy gate's DraftValidator rule plus the filtered unique indexes
// on Equipment (ConfigureEquipment). Migration ScriptForeignKeysAndExternalIdUniqueness drops the table and
// sp_ReleaseExternalIdReservation, refusing (THROW) while any row exists so no history is silently deleted.
// ConfigureDriverHostStatus is GONE. The DriverHostStatus table held per-host
// connectivity that a publisher hosted service was supposed to upsert from each driver node. That
@@ -729,7 +711,10 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
e.Property(x => x.Language).HasMaxLength(16);
e.Property(x => x.RowVersion).IsRowVersion();
e.HasIndex(x => x.ScriptId).IsUnique().HasDatabaseName("UX_Script_LogicalId");
// The logical id is the principal key of VirtualTag.ScriptId / ScriptedAlarm.PredicateScriptId
// (lmxopcua#1040). An alternate key is a unique constraint, so it replaces the former unique index of
// the same name instead of sitting beside it.
e.HasAlternateKey(x => x.ScriptId).HasName("UX_Script_LogicalId");
e.HasIndex(x => x.SourceHash).HasDatabaseName("IX_Script_SourceHash");
});
}
@@ -757,6 +742,15 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
e.HasIndex(x => x.VirtualTagId).IsUnique().HasDatabaseName("UX_VirtualTag_LogicalId");
e.HasIndex(x => new { x.EquipmentId, x.Name }).IsUnique().HasDatabaseName("UX_VirtualTag_EquipmentPath");
e.HasIndex(x => x.ScriptId).HasDatabaseName("IX_VirtualTag_Script");
// lmxopcua#1040 (#978 C-2 follow-up): a real FK. The deploy gate's VirtualTagScriptNotFound rule and the
// /scripts in-use delete guard still name the problem; this makes the database refuse it too (a delete
// racing a new reference, a hand edit). Restrict: deleting an in-use script is an error, never a cascade.
e.HasOne<Script>().WithMany()
.HasForeignKey(x => x.ScriptId)
.HasPrincipalKey(x => x.ScriptId)
.OnDelete(DeleteBehavior.Restrict)
.HasConstraintName("FK_VirtualTag_Script");
});
}
@@ -783,6 +777,13 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
e.HasIndex(x => x.ScriptedAlarmId).IsUnique().HasDatabaseName("UX_ScriptedAlarm_LogicalId");
e.HasIndex(x => new { x.EquipmentId, x.Name }).IsUnique().HasDatabaseName("UX_ScriptedAlarm_EquipmentPath");
e.HasIndex(x => x.PredicateScriptId).HasDatabaseName("IX_ScriptedAlarm_Script");
// lmxopcua#1040: as FK_VirtualTag_Script — the predicate script must exist; deleting it is refused.
e.HasOne<Script>().WithMany()
.HasForeignKey(x => x.PredicateScriptId)
.HasPrincipalKey(x => x.ScriptId)
.OnDelete(DeleteBehavior.Restrict)
.HasConstraintName("FK_ScriptedAlarm_Script");
});
}
@@ -1,54 +0,0 @@
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Queries;
/// <summary>One displayed <c>ExternalIdReservation</c> row (only the columns the /reservations page shows).</summary>
/// <param name="Kind">ZTag or SAPID.</param>
/// <param name="Value">The reserved external id.</param>
/// <param name="EquipmentUuid">Owning equipment.</param>
/// <param name="ClusterId">Cluster it was published in.</param>
/// <param name="ReleasedAt">When it was released, or null while active.</param>
public sealed record ReservationRow(ReservationKind Kind, string Value, Guid EquipmentUuid, string ClusterId, DateTime? ReleasedAt);
/// <summary>A bounded page of reservations plus the total matching the filter.</summary>
/// <param name="Rows">At most <c>pageSize</c> rows, ordered by kind then value.</param>
/// <param name="Total">All rows matching the filter (so the page can say "showing N of M").</param>
public sealed record ReservationPage(IReadOnlyList<ReservationRow> Rows, int Total);
/// <summary>
/// The /reservations page's read (lmxopcua#996, review A-8): active rows by default, projected to the displayed columns and
/// capped — the page used to render every row, released ones included, which accumulate for the life of the database.
/// </summary>
public static class ReservationListQuery
{
/// <summary>Rows shown per page (the cluster-audit page's size).</summary>
public const int DefaultPageSize = 200;
/// <summary>The filtered, ordered, projected query (exposed so a test can pin its SQL shape).</summary>
/// <param name="db">The config DB context.</param>
/// <param name="includeReleased">True to include released rows.</param>
/// <returns>The unbounded ordered projection.</returns>
public static IQueryable<ReservationRow> Query(OtOpcUaConfigDbContext db, bool includeReleased)
{
var rows = db.ExternalIdReservations.AsNoTracking().AsQueryable();
if (!includeReleased) rows = rows.Where(r => r.ReleasedAt == null);
return rows.OrderBy(r => r.Kind).ThenBy(r => r.Value)
.Select(r => new ReservationRow(r.Kind, r.Value, r.EquipmentUuid, r.ClusterId, r.ReleasedAt));
}
/// <summary>Loads one capped page and the total count for the filter.</summary>
/// <param name="db">The config DB context.</param>
/// <param name="includeReleased">True to include released rows.</param>
/// <param name="pageSize">Maximum rows returned.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>The page and the total.</returns>
public static async Task<ReservationPage> LoadAsync(
OtOpcUaConfigDbContext db, bool includeReleased, int pageSize = DefaultPageSize, CancellationToken ct = default)
{
var query = Query(db, includeReleased);
var total = await query.CountAsync(ct);
var rows = await query.Take(pageSize).ToListAsync(ct);
return new ReservationPage(rows, total);
}
}
@@ -77,7 +77,4 @@ public sealed class DraftSnapshot
/// composer ships the keys a driver-only node authenticates against from the one consistent read.
/// </summary>
public IReadOnlyList<ApiKey> ApiKeys { get; init; } = [];
/// <summary>Active reservations (<c>ReleasedAt IS NULL</c>) for pre-flight.</summary>
public IReadOnlyList<ExternalIdReservation> ActiveReservations { get; init; } = [];
}
@@ -165,9 +165,5 @@ 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),
ActiveReservations = await db.ExternalIdReservations
.AsNoTracking()
.Where(r => r.ReleasedAt == null) // active only — matches DraftSnapshot.ActiveReservations semantics
.ToListAsync(ct),
};
}
@@ -28,7 +28,6 @@ public static class DraftValidator
ValidateUnsSegments(draft, errors);
ValidateDanglingReferences(draft, errors);
ValidateEquipmentExternalIdUniqueness(draft, errors);
ValidateReservationPreflight(draft, errors);
ValidateEquipmentIdDerivation(draft, errors);
// v3 rules. The retired rules ValidateSameClusterNamespaceBinding (Namespace entity gone)
@@ -1069,9 +1068,10 @@ public static class DraftValidator
/// <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.
/// former writer of the reservation ledger (<c>sp_PublishGeneration</c>) is gone, and the ledger itself was
/// retired by lmxopcua#1049; the draft snapshot is the whole config DB (every cluster), so the duplicate check
/// is done here, on the draft, which IS the authority. The filtered unique indexes <c>UX_Equipment_ZTag</c> /
/// <c>UX_Equipment_SAPID</c> are the storage backstop (never stricter than this rule).
/// Compared trimmed and case-insensitively (the DB collation is); blank values mean "no identifier".
/// </summary>
private static void ValidateEquipmentExternalIdUniqueness(DraftSnapshot draft, List<ValidationError> errors)
@@ -1098,29 +1098,6 @@ public static class DraftValidator
Check("SAPID", e => e.SAPID);
}
private static void ValidateReservationPreflight(DraftSnapshot draft, List<ValidationError> errors)
{
var activeByKindValue = draft.ActiveReservations
.ToDictionary(r => (r.Kind, r.Value), r => r.EquipmentUuid);
foreach (var eq in draft.Equipment)
{
if (eq.ZTag is not null &&
activeByKindValue.TryGetValue((ReservationKind.ZTag, eq.ZTag), out var ztagOwner) &&
ztagOwner != eq.EquipmentUuid)
errors.Add(new("BadDuplicateExternalIdentifier",
$"ZTag '{eq.ZTag}' is already reserved by EquipmentUuid '{ztagOwner}'",
eq.EquipmentId));
if (eq.SAPID is not null &&
activeByKindValue.TryGetValue((ReservationKind.SAPID, eq.SAPID), out var sapOwner) &&
sapOwner != eq.EquipmentUuid)
errors.Add(new("BadDuplicateExternalIdentifier",
$"SAPID '{eq.SAPID}' is already reserved by EquipmentUuid '{sapOwner}'",
eq.EquipmentId));
}
}
/// <summary>EquipmentId = 'EQ-' + lowercase first 12 hex chars of the UUID.</summary>
/// <param name="uuid">The equipment UUID to derive the ID from.</param>
/// <returns>The derived <c>EQ-</c>-prefixed EquipmentId.</returns>
@@ -28,7 +28,6 @@
<NavRailItem Href="/raw" Text="Raw" />
<NavRailItem Href="/deployments" Text="Deployments" />
</AuthorizeView>
<NavRailItem Href="/reservations" Text="Reservations" />
<NavRailItem Href="/certificates" Text="Certificates" />
</NavRailSection>
<NavRailSection Title="Scripting" Key="scripting">
@@ -1,82 +0,0 @@
@page "/reservations"
@attribute [Authorize(Policy = AdminUiPolicies.AuthenticatedRead)]
@rendermode RenderMode.InteractiveServer
@using Microsoft.EntityFrameworkCore
@using ZB.MOM.WW.OtOpcUa.Configuration
@using ZB.MOM.WW.OtOpcUa.Configuration.Queries
@inject IDbContextFactory<OtOpcUaConfigDbContext> DbFactory
<PageErrorBoundary>
<PageTitle>External ID reservations · OtOpcUa</PageTitle>
<div class="page-head">
<h1>External ID reservations</h1>
<span class="spacer"></span>
<label class="form-check-label"><input type="checkbox" class="form-check-input" checked="@_includeReleased" @onchange="ToggleReleased" /> Show released</label>
</div>
@if (_rows is null)
{
<p>Loading…</p>
}
else
{
<section class="panel rise mt-3" style="animation-delay:.08s">
<h2 class="panel-head">@(_total > _rows.Count ? $"Showing {_rows.Count} of {_total}" : _total.ToString()) @(_includeReleased ? "" : "active ")reservation@(_total == 1 ? "" : "s")</h2>
@if (_rows.Count == 0)
{
<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
{
<div class="table-wrap" role="region" aria-label="External ID reservations" tabindex="0">
<table class="data-table">
<thead>
<tr>
<th scope="col">Kind</th>
<th scope="col">Value</th>
<th scope="col">Equipment UUID</th>
<th scope="col">Cluster</th>
@if (_includeReleased) { <th scope="col">Released</th> }
</tr>
</thead>
<tbody>
@foreach (var r in _rows)
{
<tr>
<td><span class="chip chip-idle">@r.Kind</span></td>
<td><span class="mono">@r.Value</span></td>
<td><span class="mono small">@r.EquipmentUuid</span></td>
<td><span class="mono small">@r.ClusterId</span></td>
@if (_includeReleased) { <td><span class="mono small">@(r.ReleasedAt?.ToString("u") ?? "active")</span></td> }
</tr>
}
</tbody>
</table>
</div>
}
</section>
}
</PageErrorBoundary>
@code {
private IReadOnlyList<ReservationRow>? _rows;
private int _total;
private bool _includeReleased;
protected override async Task OnInitializedAsync() => await LoadAsync();
private async Task ToggleReleased(ChangeEventArgs e)
{
_includeReleased = e.Value is true;
await LoadAsync();
}
private async Task LoadAsync()
{
// Active rows only by default, projected to the shown columns and capped (#996 / A-8).
await using var db = await DbFactory.CreateDbContextAsync();
var page = await ReservationListQuery.LoadAsync(db, _includeReleased);
_rows = page.Rows;
_total = page.Total;
}
}
@@ -233,8 +233,10 @@ else
var entity = await db.Scripts.FirstOrDefaultAsync(s => s.ScriptId == intent.Id);
if (!Current(generation)) return;
if (entity is null) { Nav.NavigateTo("/scripts"); return; }
// lmxopcua#978 (review C-2): no FK protects a script in use, so refuse here and name the users —
// a deleted predicate used to drop its scripted alarm silently on the next green deploy.
// lmxopcua#978 (review C-2): refuse here and name the users — a deleted predicate used to drop its
// scripted alarm silently on the next green deploy. FK_VirtualTag_Script / FK_ScriptedAlarm_Script
// (lmxopcua#1040) back this for a reference added concurrently; Calculation tags (TagConfig JSON) only
// have this check.
var inUse = await ZB.MOM.WW.OtOpcUa.AdminUI.Uns.ScriptUsage.DescribeBlockingUsageAsync(db, intent.Id);
if (!Current(generation)) return;
if (inUse is not null)
@@ -250,6 +252,7 @@ else
if (Current(generation)) Nav.NavigateTo("/scripts");
}
catch (DbUpdateConcurrencyException) { if (Current(generation)) _error = "Another user changed this script while you were viewing it."; }
catch (DbUpdateException) { if (Current(generation)) _error = "Not deleted: a virtual tag or scripted alarm started using this script meanwhile. Reload to see its users."; }
catch (Exception ex) { if (Current(generation)) _error = $"Delete failed: {ex.Message}."; }
finally { if (Current(generation)) _busy = false; }
}
@@ -117,12 +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">Must be unique fleet-wide (case-insensitive); a duplicate is rejected when you deploy.</div>
<div id='@FieldId("eq-ztag-hint")' class="form-text">Must be unique fleet-wide (case-insensitive); a value another equipment holds is refused on save.</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 class="form-text">Must be unique fleet-wide (case-insensitive); a value another equipment holds is refused on save.</div>
</div>
</div>
<div class="mb-3">
@@ -887,6 +887,8 @@ public sealed class UnsTreeService(
if (EquipmentLengthError(input) is { } tooLong) return new UnsMutationResult(false, tooLong);
if (await ExternalIdClashAsync(db, input, excludeEquipmentId: null, ct) is { } clash) return new UnsMutationResult(false, clash);
// v3: equipment no longer binds a driver — the reference-only Tags tab points at raw tags — so
// the old driver-cluster guard is gone.
@@ -901,8 +903,8 @@ public sealed class UnsTreeService(
UnsLineId = input.UnsLineId,
Name = input.Name,
MachineCode = input.MachineCode,
ZTag = string.IsNullOrWhiteSpace(input.ZTag) ? null : input.ZTag,
SAPID = string.IsNullOrWhiteSpace(input.SAPID) ? null : input.SAPID,
ZTag = ExternalId(input.ZTag),
SAPID = ExternalId(input.SAPID),
Manufacturer = input.Manufacturer,
Model = input.Model,
SerialNumber = input.SerialNumber,
@@ -921,7 +923,7 @@ public sealed class UnsTreeService(
}
catch (DbUpdateException)
{
return new UnsMutationResult(false, DuplicateEquipmentName(input.Name) + " (or a value was rejected by the database) - reload and retry.");
return new UnsMutationResult(false, DuplicateEquipmentName(input.Name) + " (or another equipment now holds this MachineCode, ZTag or SAPID) - reload and retry.");
}
}
@@ -947,6 +949,20 @@ public sealed class UnsTreeService(
.Select(e => (e.UnsLineId, e.Name))
.ToHashSet(LineNameComparer.Instance);
// lmxopcua#1049: ZTag / SAPID are unique fleet-wide (UX_Equipment_ZTag / UX_Equipment_SAPID, and the deploy
// gate). Owners already in the DB plus those claimed earlier in this batch, case-insensitive as both are — a
// clash would otherwise fail the WHOLE batch at SaveChanges with no row named.
var ids = await db.Equipment.AsNoTracking()
.Where(e => e.ZTag != null || e.SAPID != null)
.Select(e => new { e.EquipmentId, e.ZTag, e.SAPID }).ToListAsync(ct);
var zTagOwner = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var sapIdOwner = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var e in ids)
{
if (ExternalId(e.ZTag) is { } z) zTagOwner.TryAdd(z, e.EquipmentId);
if (ExternalId(e.SAPID) is { } p) sapIdOwner.TryAdd(p, e.EquipmentId);
}
var inserted = 0;
var skipped = 0;
var errors = new List<string>();
@@ -987,6 +1003,20 @@ public sealed class UnsTreeService(
continue;
}
var rowZTag = ExternalId(row.ZTag);
var rowSapId = ExternalId(row.SAPID);
if (rowZTag is not null && zTagOwner.TryGetValue(rowZTag, out var zOwner))
{
errors.Add($"Row '{row.MachineCode}': {ExternalIdTaken("ZTag", rowZTag, zOwner)}");
continue;
}
if (rowSapId is not null && sapIdOwner.TryGetValue(rowSapId, out var sOwner))
{
errors.Add($"Row '{row.MachineCode}': {ExternalIdTaken("SAPID", rowSapId, sOwner)}");
continue;
}
// v3: equipment no longer binds a driver, so there is no per-row driver-cluster guard.
var uuid = Guid.NewGuid();
@@ -1000,8 +1030,8 @@ public sealed class UnsTreeService(
UnsLineId = row.UnsLineId,
Name = row.Name,
MachineCode = row.MachineCode,
ZTag = string.IsNullOrWhiteSpace(row.ZTag) ? null : row.ZTag,
SAPID = string.IsNullOrWhiteSpace(row.SAPID) ? null : row.SAPID,
ZTag = ExternalId(row.ZTag),
SAPID = ExternalId(row.SAPID),
Manufacturer = row.Manufacturer,
Model = row.Model,
SerialNumber = row.SerialNumber,
@@ -1015,6 +1045,8 @@ public sealed class UnsTreeService(
});
existing.Add(row.MachineCode);
existingNames.Add((row.UnsLineId, row.Name));
if (rowZTag is not null) zTagOwner[rowZTag] = equipmentId;
if (rowSapId is not null) sapIdOwner[rowSapId] = equipmentId;
inserted++;
}
@@ -1028,7 +1060,7 @@ public sealed class UnsTreeService(
{
// A concurrent writer slipped a clashing row past the pre-checks: the batch is atomic, so
// nothing was imported.
errors.Add("Import failed - a concurrent change clashed with this file (duplicate name or MachineCode). Nothing was imported; reload and retry.");
errors.Add("Import failed - a concurrent change clashed with this file (duplicate name, MachineCode, ZTag or SAPID). Nothing was imported; reload and retry.");
return new EquipmentImportResult(0, skipped, errors);
}
}
@@ -1066,14 +1098,16 @@ public sealed class UnsTreeService(
if (EquipmentLengthError(input) is { } tooLong) return new UnsMutationResult(false, tooLong);
if (await ExternalIdClashAsync(db, input, equipmentId, ct) is { } clash) return new UnsMutationResult(false, clash);
// v3: equipment no longer binds a driver — no driver-cluster guard.
// Equipment↔driver binding retired in v3 — no DriverInstanceId column remains.
entity.UnsLineId = input.UnsLineId;
entity.Name = input.Name;
entity.MachineCode = input.MachineCode;
entity.ZTag = string.IsNullOrWhiteSpace(input.ZTag) ? null : input.ZTag;
entity.SAPID = string.IsNullOrWhiteSpace(input.SAPID) ? null : input.SAPID;
entity.ZTag = ExternalId(input.ZTag);
entity.SAPID = ExternalId(input.SAPID);
entity.Manufacturer = input.Manufacturer;
entity.Model = input.Model;
entity.SerialNumber = input.SerialNumber;
@@ -1096,7 +1130,7 @@ public sealed class UnsTreeService(
}
catch (DbUpdateException)
{
return new UnsMutationResult(false, DuplicateEquipmentName(input.Name) + " (or a value was rejected by the database) - reload and retry.");
return new UnsMutationResult(false, DuplicateEquipmentName(input.Name) + " (or another equipment now holds this MachineCode, ZTag or SAPID) - reload and retry.");
}
}
@@ -1362,6 +1396,47 @@ public sealed class UnsTreeService(
/// otherwise (no slash-token, or all resolve). Replaces the v2 <c>DeriveEquipmentBase(empty)→null</c>
/// check, which rejected ALL <c>{{equip}}</c> VirtualTags with a now-impossible "add a driver tag" message.
/// </summary>
/// <summary>A ZTag / SAPID as stored: trimmed, and blank means "no identifier" (NULL) — the deploy gate's reading.</summary>
private static string? ExternalId(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
private static string ExternalIdTaken(string label, string value, string owner) =>
$"{label} '{value}' is already set on equipment '{owner}'; a {label} must be unique fleet-wide.";
/// <summary>
/// lmxopcua#1049: the authoring mirror of the deploy gate's <c>BadDuplicateExternalIdentifier</c> rule and of the
/// <c>UX_Equipment_ZTag</c> / <c>UX_Equipment_SAPID</c> unique indexes, naming the equipment that already holds the
/// value. Compared by the database (case-insensitive collation on SQL Server).
/// </summary>
private static async Task<string?> ExternalIdClashAsync(
OtOpcUaConfigDbContext db, EquipmentInput input, string? excludeEquipmentId, CancellationToken ct)
{
if (ExternalId(input.ZTag) is { } zTag
&& await db.Equipment.Where(e => e.ZTag == zTag && e.EquipmentId != excludeEquipmentId)
.Select(e => e.EquipmentId).FirstOrDefaultAsync(ct) is { } zOwner)
return ExternalIdTaken("ZTag", zTag, zOwner);
if (ExternalId(input.SAPID) is { } sapId
&& await db.Equipment.Where(e => e.SAPID == sapId && e.EquipmentId != excludeEquipmentId)
.Select(e => e.EquipmentId).FirstOrDefaultAsync(ct) is { } sOwner)
return ExternalIdTaken("SAPID", sapId, sOwner);
return null;
}
/// <summary>
/// lmxopcua#1040: a VirtualTag's script / a scripted alarm's predicate script must exist — the authoring mirror of
/// the deploy gate's <c>VirtualTagScriptNotFound</c> / <c>ScriptedAlarmScriptNotFound</c> rules and of the
/// <c>FK_VirtualTag_Script</c> / <c>FK_ScriptedAlarm_Script</c> constraints, said before the database refuses it.
/// </summary>
private static async Task<UnsMutationResult?> ScriptMissingAsync(OtOpcUaConfigDbContext db, string? scriptId, CancellationToken ct) =>
!string.IsNullOrEmpty(scriptId) && await db.Scripts.AnyAsync(s => s.ScriptId == scriptId, ct)
? null
: new UnsMutationResult(false, $"Script '{scriptId}' does not exist — pick an existing script.");
/// <summary>The save-time refusal when a pre-checked script vanished (or another constraint clashed) concurrently.</summary>
private static string ScriptGoneOrClash(string? scriptId) =>
$"The save was refused by the database: script '{scriptId}' may have been deleted meanwhile, or a name now clashes. Reload and retry.";
private static async Task<UnsMutationResult?> ValidateEquipTokenAsync(
OtOpcUaConfigDbContext db, string equipmentId, string scriptId, CancellationToken ct)
{
@@ -1465,6 +1540,8 @@ public sealed class UnsTreeService(
var nameGuard = await _guard.CheckAsync(equipmentId, input.Name, EffectiveNameSourceKind.VirtualTag, null, ct);
if (nameGuard is not null) return new UnsMutationResult(false, nameGuard);
if (await ScriptMissingAsync(db, input.ScriptId, ct) is { } missingScript) return missingScript;
var equipGuard = await ValidateEquipTokenAsync(db, equipmentId, input.ScriptId, ct);
if (equipGuard is not null) return equipGuard.Value;
@@ -1480,8 +1557,15 @@ public sealed class UnsTreeService(
Historize = input.Historize,
Enabled = input.Enabled,
});
await db.SaveChangesAsync(ct);
return new UnsMutationResult(true, null);
try
{
await db.SaveChangesAsync(ct);
return new UnsMutationResult(true, null);
}
catch (DbUpdateException)
{
return new UnsMutationResult(false, ScriptGoneOrClash(input.ScriptId));
}
}
/// <inheritdoc />
@@ -1518,6 +1602,8 @@ public sealed class UnsTreeService(
var nameGuard = await _guard.CheckAsync(entity.EquipmentId, input.Name, EffectiveNameSourceKind.VirtualTag, virtualTagId, ct);
if (nameGuard is not null) return new UnsMutationResult(false, nameGuard);
if (await ScriptMissingAsync(db, input.ScriptId, ct) is { } missingScript) return missingScript;
var equipGuard = await ValidateEquipTokenAsync(db, entity.EquipmentId, input.ScriptId, ct);
if (equipGuard is not null) return equipGuard.Value;
@@ -1539,6 +1625,10 @@ public sealed class UnsTreeService(
{
return new UnsMutationResult(false, "Another user changed this virtual tag while you were editing.");
}
catch (DbUpdateException)
{
return new UnsMutationResult(false, ScriptGoneOrClash(input.ScriptId));
}
}
/// <inheritdoc />
@@ -1789,6 +1879,8 @@ public sealed class UnsTreeService(
if (nameGuard is not null) return new UnsMutationResult(false, nameGuard);
// v3: {{equip}}/<RefName> in the predicate script or message template must resolve.
if (await ScriptMissingAsync(db, input.PredicateScriptId, ct) is { } missingScript) return missingScript;
var equipGuard = await ValidateEquipTokenForAlarmAsync(db, equipmentId, input.PredicateScriptId, input.MessageTemplate, ct);
if (equipGuard is not null) return equipGuard.Value;
@@ -1805,8 +1897,15 @@ public sealed class UnsTreeService(
Retain = input.Retain,
Enabled = input.Enabled,
});
await db.SaveChangesAsync(ct);
return new UnsMutationResult(true, null, input.ScriptedAlarmId);
try
{
await db.SaveChangesAsync(ct);
return new UnsMutationResult(true, null, input.ScriptedAlarmId);
}
catch (DbUpdateException)
{
return new UnsMutationResult(false, ScriptGoneOrClash(input.PredicateScriptId));
}
}
/// <inheritdoc />
@@ -1827,6 +1926,8 @@ public sealed class UnsTreeService(
if (nameGuard is not null) return new UnsMutationResult(false, nameGuard);
// v3: {{equip}}/<RefName> in the predicate script or message template must resolve.
if (await ScriptMissingAsync(db, input.PredicateScriptId, ct) is { } missingScript) return missingScript;
var equipGuard = await ValidateEquipTokenForAlarmAsync(db, entity.EquipmentId, input.PredicateScriptId, input.MessageTemplate, ct);
if (equipGuard is not null) return equipGuard.Value;
@@ -1849,6 +1950,10 @@ public sealed class UnsTreeService(
{
return new UnsMutationResult(false, "Another user changed this scripted alarm while you were editing.");
}
catch (DbUpdateException)
{
return new UnsMutationResult(false, ScriptGoneOrClash(input.PredicateScriptId));
}
}
/// <inheritdoc />
@@ -530,10 +530,6 @@ public sealed class AdminOperationsActor : ReceiveActor
// derivation, cross-cluster/namespace binding, driver-namespace compat, signal collisions,
// …) gates the deploy. A green build in this repo does not prove the config is valid; this
// is the last guard before a bad address space (or a non-derived EquipmentId) ships.
// NOTE: a BadDuplicateExternalIdentifier rejection from the reservation pre-flight can
// (rarely) be a false positive if an external-id reservation release has not yet been
// committed/visible when the snapshot is read — operators seeing a spurious one should
// check ExternalIdReservation state before re-submitting.
var draft = await DraftSnapshotFactory.FromConfigDbAsync(db);
phases.Mark("snapshot-read");
var errors = DraftValidator.Validate(draft).ToList();