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
@@ -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();