Merge ConfigDb follow-ups: script FKs + ZTag/SAPID filtered unique indexes, ExternalIdReservation retired (#1040/#1049, migration ScriptForeignKeysAndExternalIdUniqueness with pre-check), SqlNamedQueryInvalid deploy rule (#1058), read-only otopcua-preflight upgrade tool (#1013/#1015/#1021)

# Conflicts:
#	docs/VirtualTags.md
This commit is contained in:
Joseph Doherty
2026-12-03 15:42:25 -05:00
56 changed files with 4623 additions and 710 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;
}
}
@@ -255,8 +255,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)
@@ -272,6 +274,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">
@@ -139,13 +139,13 @@ public sealed class UnsTreeService(
// Backing tag missing (should not happen — raw-tag delete is reference-blocked); surface a
// clearly-degraded row rather than dropping it so the operator can remove the dangling ref.
rows.Add(new EquipmentReferenceRow(
r.UnsTagReferenceId, r.DisplayNameOverride ?? "(missing tag)", "(missing tag)",
r.UnsTagReferenceId, EquipmentReferenceMap.EffectiveName(r.DisplayNameOverride, "(missing tag)")!, "(missing tag)",
"", TagAccessLevel.Read, r.DisplayNameOverride, r.SortOrder, r.RowVersion));
continue;
}
var rawPath = resolver?.TryBuildTagPath(tag.DeviceId, tag.TagGroupId, tag.Name) ?? tag.Name;
var effectiveName = string.IsNullOrEmpty(r.DisplayNameOverride) ? tag.Name : r.DisplayNameOverride;
var effectiveName = EquipmentReferenceMap.EffectiveName(r.DisplayNameOverride, tag.Name)!;
rows.Add(new EquipmentReferenceRow(
r.UnsTagReferenceId, effectiveName, rawPath, tag.DataType, tag.AccessLevel,
r.DisplayNameOverride, r.SortOrder, r.RowVersion));
@@ -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)
{
@@ -1412,9 +1487,8 @@ public sealed class UnsTreeService(
var effectiveNames = new HashSet<string>(StringComparer.Ordinal);
foreach (var r in refs)
{
var eff = string.IsNullOrEmpty(r.DisplayNameOverride)
? (tagNameById.TryGetValue(r.TagId, out var n) ? n : null)
: r.DisplayNameOverride;
var eff = EquipmentReferenceMap.EffectiveName(
r.DisplayNameOverride, tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
if (!string.IsNullOrEmpty(eff)) effectiveNames.Add(eff!);
}
return effectiveNames;
@@ -1466,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;
@@ -1481,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 />
@@ -1519,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;
@@ -1540,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 />
@@ -1790,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;
@@ -1806,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 />
@@ -1828,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;
@@ -1850,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 />
@@ -550,83 +550,23 @@ 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();
// Cluster-topology guard. The SQL
// CK_ServerCluster_RedundancyMode_NodeCount CHECK enforces the (NodeCount, RedundancyMode)
// pair on the row itself, but it cannot see the per-node ClusterNode.Enabled flag — an
// operator can disable a node (effective enabled-count = 1) while leaving RedundancyMode at
// Hot/Warm and the constraint stays green, which would boot the runtime into an
// InvalidTopology band. ValidateClusterTopology catches that drift; it is not part of
// DraftValidator.Validate, so it runs separately here over the snapshot's cluster/node rows.
// Errors fold into the same reject summary alongside the snapshot rules so a deploy failing
// either check is rejected with both sets of messages. ClusterId-ordered for a deterministic summary.
// R03:3.2 — both come off the SAME snapshot read as every other table (one SNAPSHOT
// transaction), not a second query that could observe a later edit.
var clusters = draft.ServerClusters.OrderBy(c => c.ClusterId, StringComparer.Ordinal).ToList();
var nodesByCluster = draft.ClusterNodes
.GroupBy(n => n.ClusterId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.ToList(), StringComparer.Ordinal);
foreach (var cluster in clusters)
{
var nodes = nodesByCluster.TryGetValue(cluster.ClusterId, out var ns)
? (IReadOnlyList<ClusterNode>)ns
: [];
errors.AddRange(DraftValidator.ValidateClusterTopology(cluster, nodes));
}
// Deploy-time TagConfig strictness inspection over equipment tags. The
// driver-typed EquipmentTagConfigInspector surfaces every blob the driver's own reader would
// REJECT — a present-but-invalid enum value, an absent or malformed address field, a
// structurally-unparseable TagConfig — each of which makes the driver skip the tag so it reads
// BadNodeIdUnknown forever. (The runtime used to silently default a typo'd enum;
// it now rejects the tag, so these warnings describe rejections.) In Warn mode
// (default) these are non-blocking (logged + appended to the accepted result Message); in Error
// mode they fold into the reject list so a typo'd config cannot be re-deployed until fixed.
// Running servers are untouched either way — the gate only sees re-deploys.
// v3: a raw Tag's driver is resolved via its Device (Tag no longer carries EquipmentId /
// DriverInstanceId). Inspect EVERY raw tag's TagConfig against its device's driver type.
var driverTypeById = draft.DriverInstances
.GroupBy(d => d.DriverInstanceId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First().DriverType, StringComparer.Ordinal);
var driverByDevice = draft.Devices
.GroupBy(d => d.DeviceId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First().DriverInstanceId, StringComparer.Ordinal);
var deviceConfigById = draft.Devices
.GroupBy(d => d.DeviceId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First().DeviceConfig, StringComparer.Ordinal);
var tagConfigWarnings = new List<(string TagId, string Text)>();
foreach (var t in draft.Tags)
{
if (!driverByDevice.TryGetValue(t.DeviceId, out var driverInstanceId)) continue;
if (!driverTypeById.TryGetValue(driverInstanceId, out var driverType)) continue;
foreach (var w in EquipmentTagConfigInspector.Inspect(
driverType, t.TagConfig, deviceConfigById.GetValueOrDefault(t.DeviceId)))
tagConfigWarnings.Add((t.TagId, $"tag '{t.TagId}': {w}"));
}
if (tagConfigWarnings.Count > 0)
{
if (_tagConfigValidationMode == TagConfigValidationMode.Error)
errors.AddRange(tagConfigWarnings.Select(x => new ValidationError("TagConfigInvalid", x.Text, x.TagId)));
else
foreach (var x in tagConfigWarnings)
_log.Warning("StartDeployment: TagConfig warning (Warn mode, non-blocking): {Warning}", x.Text);
}
// The rule pass — DraftValidator, per-cluster topology, TagConfig inspection, the non-blocking Sql / data-
// connection warnings — is DeployGateRules (shared with the upgrade preflight, lmxopcua#1013/#1015/#1058).
// R03:3.2: every check runs off this ONE snapshot read.
var gate = DeployGateRules.Evaluate(draft, _tagConfigValidationMode);
var errors = gate.Errors.ToList();
foreach (var w in gate.TagConfigWarnings)
_log.Warning("StartDeployment: TagConfig warning (Warn mode, non-blocking): {Warning}", w.Message);
// lmxopcua#781 item 3: always non-blocking (independent of TagConfigValidationMode) — the Tag
// entity's Writable flag and the Sql blob's "writable" disagree.
var writableWarnings = SqlTagDeployChecks.WritableMismatchWarnings(draft);
foreach (var w in writableWarnings)
foreach (var w in gate.SqlWritableWarnings)
_log.Warning("StartDeployment: Sql writable mismatch (non-blocking): {Warning}", w);
// A2b (plan §6): Σ MaxConditions × 49 of a consumer node's alarm mappings over the host cap — non-blocking.
foreach (var w in DataConnectionValidator.DeployWarnings(draft))
foreach (var w in gate.DataConnectionWarnings)
_log.Warning("StartDeployment: data-connection warning (non-blocking): {Warning}", w);
phases.Mark("validate");
@@ -749,8 +689,8 @@ public sealed class AdminOperationsActor : ReceiveActor
// the operator sees the non-blocking strictness findings on a successful deploy.
var messageParts = new List<string>();
if (advisory is not null) messageParts.Add(advisory);
messageParts.AddRange(tagConfigWarnings.Select(x => x.Text));
messageParts.AddRange(writableWarnings);
messageParts.AddRange(gate.TagConfigWarnings.Select(x => x.Message));
messageParts.AddRange(gate.SqlWritableWarnings);
messageParts.AddRange(scriptWarnings);
var acceptedMessage = messageParts.Count > 0 ? string.Join("; ", messageParts) : null;
@@ -0,0 +1,85 @@
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
/// <summary>
/// The deploy gate's rule pass over one <see cref="DraftSnapshot"/> — everything <c>AdminOperationsActor</c> checks
/// before the script compile gate (<see cref="DeployScriptGate"/>), stated once so the upgrade preflight
/// (<c>Preflight.UpgradePreflight</c>, lmxopcua#1013/#1015/#1021/#1058) reports exactly what the next deploy would
/// refuse instead of a re-implementation that drifts.
/// </summary>
public static class DeployGateRules
{
/// <summary>The deploy-gate error code a TagConfig inspection finding carries in Error mode.</summary>
public const string TagConfigInvalidCode = "TagConfigInvalid";
/// <summary>What the rule pass found.</summary>
/// <param name="Errors">Blocking: <see cref="DraftValidator.Validate"/>, the per-cluster topology check, and — in
/// <see cref="TagConfigValidationMode.Error"/> — the TagConfig inspection.</param>
/// <param name="TagConfigWarnings">The TagConfig inspection in <see cref="TagConfigValidationMode.Warn"/> mode
/// (non-blocking); empty in Error mode, where they are in <paramref name="Errors"/>.</param>
/// <param name="SqlWritableWarnings">Always non-blocking (lmxopcua#781 item 3).</param>
/// <param name="DataConnectionWarnings">Always non-blocking (data-connection alarm-mapping budget).</param>
public sealed record Result(
IReadOnlyList<ValidationError> Errors,
IReadOnlyList<ValidationError> TagConfigWarnings,
IReadOnlyList<string> SqlWritableWarnings,
IReadOnlyList<string> DataConnectionWarnings);
/// <summary>Runs every rule over the snapshot.</summary>
/// <param name="draft">The whole-DB snapshot (<see cref="DraftSnapshotFactory.FromConfigDbAsync"/>).</param>
/// <param name="tagConfigMode">The configured <c>Deployment:TagConfigValidationMode</c>.</param>
/// <returns>The findings.</returns>
public static Result Evaluate(DraftSnapshot draft, TagConfigValidationMode tagConfigMode)
{
ArgumentNullException.ThrowIfNull(draft);
// Full pre-seal gate: the complete DraftValidator (one pass, all rules).
var errors = DraftValidator.Validate(draft).ToList();
// Cluster-topology guard. The SQL CK_ServerCluster_RedundancyMode_NodeCount CHECK enforces the
// (NodeCount, RedundancyMode) pair on the row itself, but it cannot see the per-node ClusterNode.Enabled
// flag — an operator can disable a node (effective enabled-count = 1) while leaving RedundancyMode at
// Hot/Warm, which would boot the runtime into an InvalidTopology band. Not part of DraftValidator.Validate,
// so it runs here over the snapshot's cluster/node rows, ClusterId-ordered for a deterministic summary.
// R03:3.2 — both come off the SAME snapshot read as every other table.
var nodesByCluster = draft.ClusterNodes
.GroupBy(n => n.ClusterId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.ToList(), StringComparer.Ordinal);
foreach (var cluster in draft.ServerClusters.OrderBy(c => c.ClusterId, StringComparer.Ordinal))
{
var nodes = nodesByCluster.TryGetValue(cluster.ClusterId, out var ns) ? (IReadOnlyList<ClusterNode>)ns : [];
errors.AddRange(DraftValidator.ValidateClusterTopology(cluster, nodes));
}
// Deploy-time TagConfig strictness inspection. The driver-typed EquipmentTagConfigInspector surfaces every
// blob the driver's own reader would REJECT — each of which makes the driver skip the tag so it reads
// BadNodeIdUnknown forever. Warn mode (default): non-blocking; Error mode: blocking. A raw Tag's driver is
// resolved via its Device.
var driverTypeById = draft.DriverInstances
.GroupBy(d => d.DriverInstanceId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First().DriverType, StringComparer.Ordinal);
var deviceById = draft.Devices
.GroupBy(d => d.DeviceId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal);
var tagConfigFindings = new List<ValidationError>();
foreach (var t in draft.Tags)
{
if (!deviceById.TryGetValue(t.DeviceId, out var device)) continue;
if (!driverTypeById.TryGetValue(device.DriverInstanceId, out var driverType)) continue;
foreach (var w in EquipmentTagConfigInspector.Inspect(driverType, t.TagConfig, device.DeviceConfig))
tagConfigFindings.Add(new ValidationError(TagConfigInvalidCode, $"tag '{t.TagId}': {w}", t.TagId));
}
IReadOnlyList<ValidationError> tagConfigWarnings = [];
if (tagConfigMode == TagConfigValidationMode.Error) errors.AddRange(tagConfigFindings);
else tagConfigWarnings = tagConfigFindings;
return new Result(
errors,
tagConfigWarnings,
SqlTagDeployChecks.WritableMismatchWarnings(draft),
DataConnectionValidator.DeployWarnings(draft));
}
}
@@ -0,0 +1,151 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.OtOpcUa.Configuration;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight;
/// <summary>
/// Lets THIS build's <see cref="OtOpcUaConfigDbContext"/> read a ConfigDb that is still on an OLDER schema — the
/// whole point of a pre-upgrade preflight is to run before the pending migrations. A table a pending migration
/// creates is read as empty (mapped to a typed zero-row query); a column a pending migration adds is left out of
/// the model (the property keeps its CLR default). Nothing else is changed, so every rule sees exactly the rows a
/// deploy right after the upgrade would see, minus data that cannot exist yet.
/// </summary>
internal static class LegacySchemaTolerance
{
/// <summary>The tables / columns of the current model that are absent from the database.</summary>
/// <param name="MissingTables">Table names, case-insensitive.</param>
/// <param name="MissingColumns">(table, column) pairs on tables that exist.</param>
internal sealed record SchemaGaps(IReadOnlySet<string> MissingTables, IReadOnlySet<(string Table, string Column)> MissingColumns)
{
/// <summary>No gap at all — the plain model reads the database.</summary>
public bool IsEmpty => MissingTables.Count == 0 && MissingColumns.Count == 0;
/// <summary>Stable text form; also the model-cache discriminator.</summary>
public string Signature =>
string.Join(";", MissingTables.Order(StringComparer.OrdinalIgnoreCase)) + "|" +
string.Join(";", MissingColumns.Select(c => $"{c.Table}.{c.Column}").Order(StringComparer.OrdinalIgnoreCase));
}
/// <summary>Compares the model's tables/columns with the database's (<c>dbo</c> schema).</summary>
/// <param name="model">The current model.</param>
/// <param name="present">Database table → its columns.</param>
/// <returns>The gaps.</returns>
internal static SchemaGaps Compare(IModel model, IReadOnlyDictionary<string, HashSet<string>> present)
{
var tables = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var columns = new HashSet<(string, string)>();
foreach (var entity in model.GetEntityTypes())
{
var table = entity.GetTableName();
if (table is null) continue;
if (!present.TryGetValue(table, out var have))
{
tables.Add(table);
continue;
}
var store = StoreObjectIdentifier.Table(table, entity.GetSchema());
foreach (var p in entity.GetProperties())
if (p.GetColumnName(store) is { } column && !have.Contains(column))
columns.Add((table, column));
}
return new SchemaGaps(tables, columns);
}
/// <summary>Configures <paramref name="builder"/> to read through <paramref name="gaps"/>.</summary>
/// <param name="builder">The options builder (SQL Server already selected).</param>
/// <param name="gaps">The gaps; nothing is changed when empty.</param>
internal static void Apply(DbContextOptionsBuilder<OtOpcUaConfigDbContext> builder, SchemaGaps gaps)
{
if (gaps.IsEmpty) return;
((IDbContextOptionsBuilderInfrastructure)builder).AddOrUpdateExtension(new GapsExtension(gaps));
builder.ReplaceService<IModelCustomizer, TolerantModelCustomizer>();
builder.ReplaceService<IModelCacheKeyFactory, GapsAwareModelCacheKeyFactory>();
}
/// <summary>Carries the gaps to the model customizer (and into the internal service-provider/model caches).</summary>
private sealed class GapsExtension(SchemaGaps gaps) : IDbContextOptionsExtension
{
public SchemaGaps Gaps { get; } = gaps;
public DbContextOptionsExtensionInfo Info => new ExtensionInfo(this);
public void ApplyServices(IServiceCollection services)
{
}
public void Validate(IDbContextOptions options)
{
}
private sealed class ExtensionInfo(GapsExtension extension) : DbContextOptionsExtensionInfo(extension)
{
public override bool IsDatabaseProvider => false;
public override string LogFragment => "LegacySchemaTolerance ";
public override int GetServiceProviderHashCode() =>
StringComparer.Ordinal.GetHashCode(((GapsExtension)Extension).Gaps.Signature);
public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) =>
other is ExtensionInfo o && o.Extension is GapsExtension g &&
string.Equals(g.Gaps.Signature, ((GapsExtension)Extension).Gaps.Signature, StringComparison.Ordinal);
public override void PopulateDebugInfo(IDictionary<string, string> debugInfo) =>
debugInfo["LegacySchemaTolerance"] = ((GapsExtension)Extension).Gaps.Signature;
}
}
/// <summary>Runs the context's own model building, then maps the gaps.</summary>
private sealed class TolerantModelCustomizer(ModelCustomizerDependencies dependencies) : RelationalModelCustomizer(dependencies)
{
public override void Customize(ModelBuilder modelBuilder, DbContext context)
{
base.Customize(modelBuilder, context);
var gaps = context.GetService<IDbContextOptions>().FindExtension<GapsExtension>()?.Gaps;
if (gaps is null) return;
var typeMappings = context.GetService<IRelationalTypeMappingSource>();
foreach (var entity in modelBuilder.Model.GetEntityTypes().ToList())
{
var table = entity.GetTableName();
if (table is null) continue;
if (gaps.MissingTables.Contains(table))
{
// A typed, zero-row stand-in: the deploy reads the table as empty, as it will be right after the
// migration creates it. Types matter only so predicates/ORDER BY over it compile.
var store = StoreObjectIdentifier.Table(table, entity.GetSchema());
var columns = entity.GetProperties().Select(p =>
{
var clr = p.GetValueConverter()?.ProviderClrType ?? p.GetProviderClrType() ?? p.ClrType;
var type = p.GetColumnType() ?? typeMappings.FindMapping(Nullable.GetUnderlyingType(clr) ?? clr)?.StoreType ?? "sql_variant";
if (type.Equals("rowversion", StringComparison.OrdinalIgnoreCase)) type = "binary(8)";
return $"CAST(NULL AS {type}) AS [{p.GetColumnName(store) ?? p.Name}]";
});
modelBuilder.Entity(entity.ClrType).ToSqlQuery($"SELECT TOP (0) {string.Join(", ", columns)}");
continue;
}
foreach (var p in entity.GetProperties().ToList())
{
var column = p.GetColumnName(StoreObjectIdentifier.Table(table, entity.GetSchema())) ?? p.Name;
if (gaps.MissingColumns.Contains((table, column)))
modelBuilder.Entity(entity.ClrType).Ignore(p.Name);
}
}
}
}
/// <summary>Two contexts over databases with different gaps must not share a cached model.</summary>
private sealed class GapsAwareModelCacheKeyFactory : IModelCacheKeyFactory
{
public object Create(DbContext context, bool designTime) =>
(context.GetType(), designTime, context.GetService<IDbContextOptions>().FindExtension<GapsExtension>()?.Gaps.Signature);
}
}
@@ -0,0 +1,146 @@
using Microsoft.Data.SqlClient;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight;
/// <summary>
/// The read-only, row-naming twins of the pre-checks inside the migrations that add constraints over existing data
/// (lmxopcua#1021): each migration THROWs and changes nothing when its data cannot hold the new constraint; these
/// list every offending row up front, so the operator can clean up before the upgrade window instead of during it.
/// Keep a new constraint-adding migration's pre-check and its entry here in step.
/// </summary>
internal static class MigrationPreChecks
{
/// <summary>One check: a SELECT whose rows are the offenders (group key in column 0, row id in column 1).</summary>
/// <param name="Migration">The migration name suffix (the part after the timestamp).</param>
/// <param name="Code">Finding code.</param>
/// <param name="Sql">The SELECT. Column 0 = group label (rows sharing it are one problem), column 1 = row id.</param>
/// <param name="Describe">Builds the message from the group label and its row ids.</param>
internal sealed record Check(string Migration, string Code, string Sql, Func<string, IReadOnlyList<string>, string> Describe);
internal const string ConfigurationGaps = "ConfigurationGapsIndexesAndRowVersions";
internal const string ScriptForeignKeys = "ScriptForeignKeysAndExternalIdUniqueness";
/// <summary>Every known check, in migration order.</summary>
internal static readonly IReadOnlyList<Check> All =
[
// lmxopcua#998 C-8: UX_NodeAcl_PrincipalScope / UX_LdapGroupRoleMapping_Group_Cluster become unfiltered, so
// NULL-keyed rows (Cluster-scope ACLs, system-wide mappings) must be unique too. PARTITION BY groups NULLs
// together and compares with the column collation — exactly what the unique index will do.
new(ConfigurationGaps, "DuplicateNodeAcl", """
SELECT CONCAT(N'cluster ''', ClusterId, N''', principal ''', Principal, N''', scope ', ScopeKind, N' ''', ISNULL(ScopeId, N'(cluster)'), N''''), NodeAclId
FROM (SELECT *, COUNT(*) OVER (PARTITION BY ClusterId, Principal, ScopeKind, ScopeId) AS n FROM [NodeAcl]) x
WHERE n > 1 ORDER BY ClusterId, Principal, ScopeKind, ScopeId, NodeAclId
""",
(key, ids) => $"{ids.Count} NodeAcl rows share {key}: {Join(ids)}. Delete or merge all but one."),
new(ConfigurationGaps, "DuplicateLdapGroupRoleMapping", """
SELECT CONCAT(N'group ''', LdapGroup, N''' in ', ISNULL(N'cluster ''' + ClusterId + N'''', N'(system-wide)')), CONVERT(nvarchar(36), Id)
FROM (SELECT *, COUNT(*) OVER (PARTITION BY LdapGroup, ClusterId) AS n FROM [LdapGroupRoleMapping]) x
WHERE n > 1 ORDER BY LdapGroup, ClusterId, Id
""",
(key, ids) => $"{ids.Count} LdapGroupRoleMapping rows share {key}: {Join(ids)}. Delete or merge all but one."),
// lmxopcua#1040 / #1049: script FKs, Script.ScriptId NOT NULL, unique ZTag / SAPID, reservation ledger dropped.
new(ScriptForeignKeys, "ScriptIdNull", """
SELECT N'Script rows with a NULL ScriptId', CONCAT(CONVERT(nvarchar(36), ScriptRowId), N' (', Name, N')')
FROM [Script] WHERE ScriptId IS NULL ORDER BY Name
""",
(_, ids) => $"{ids.Count} Script row(s) have a NULL ScriptId: {Join(ids)}. Give each a unique ScriptId or delete it."),
new(ScriptForeignKeys, "VirtualTagScriptDangling", """
SELECT CONCAT(N'missing script ''', v.ScriptId, N''''), CONCAT(v.VirtualTagId, N' (equipment ', v.EquipmentId, N', ''', v.Name, N''')')
FROM [VirtualTag] v WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.ScriptId = v.ScriptId) ORDER BY v.ScriptId, v.VirtualTagId
""",
(key, ids) => $"VirtualTag row(s) name {key}: {Join(ids)}. Point them at an existing script or delete them."),
new(ScriptForeignKeys, "ScriptedAlarmScriptDangling", """
SELECT CONCAT(N'missing predicate script ''', a.PredicateScriptId, N''''), CONCAT(a.ScriptedAlarmId, N' (equipment ', a.EquipmentId, N', ''', a.Name, N''')')
FROM [ScriptedAlarm] a WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.ScriptId = a.PredicateScriptId) ORDER BY a.PredicateScriptId, a.ScriptedAlarmId
""",
(key, ids) => $"ScriptedAlarm row(s) name {key}: {Join(ids)}. Point them at an existing script or delete them."),
new(ScriptForeignKeys, "DuplicateZTag", """
SELECT CONCAT(N'ZTag ''', ZTag, N''''), EquipmentId
FROM (SELECT *, COUNT(*) OVER (PARTITION BY ZTag) AS n FROM [Equipment] WHERE ZTag IS NOT NULL AND ZTag <> N'') x
WHERE n > 1 ORDER BY ZTag, EquipmentId
""",
(key, ids) => $"{key} is set on {ids.Count} equipment rows: {Join(ids)}. Keep it on one and clear or change the others."),
new(ScriptForeignKeys, "DuplicateSAPID", """
SELECT CONCAT(N'SAPID ''', SAPID, N''''), EquipmentId
FROM (SELECT *, COUNT(*) OVER (PARTITION BY SAPID) AS n FROM [Equipment] WHERE SAPID IS NOT NULL AND SAPID <> N'') x
WHERE n > 1 ORDER BY SAPID, EquipmentId
""",
(key, ids) => $"{key} is set on {ids.Count} equipment rows: {Join(ids)}. Keep it on one and clear or change the others."),
new(ScriptForeignKeys, "ExternalIdReservationRows", """
IF OBJECT_ID(N'[ExternalIdReservation]', N'U') IS NOT NULL
EXEC(N'SELECT N''ExternalIdReservation rows'', CONCAT(Kind, N'' '''''', Value, N'''''' -> '', CONVERT(nvarchar(36), EquipmentUuid), CASE WHEN ReleasedAt IS NULL THEN N'' (active)'' ELSE N'' (released)'' END) FROM [ExternalIdReservation] ORDER BY Kind, Value');
""",
(_, ids) => $"{ids.Count} ExternalIdReservation row(s): {Join(ids)}. The ledger is retired and its table is dropped by the migration, " +
"which refuses while it holds rows. Export them if their history matters, then DELETE FROM [ExternalIdReservation]."),
];
private const int MaxIdsNamed = 25;
private static string Join(IReadOnlyList<string> ids) =>
string.Join(", ", ids.Take(MaxIdsNamed)) + (ids.Count > MaxIdsNamed ? $" (+{ids.Count - MaxIdsNamed} more)" : string.Empty);
/// <summary>Runs every check whose migration is pending; already-applied migrations are reported as Info.</summary>
/// <param name="connection">An open connection to the ConfigDb.</param>
/// <param name="pendingMigrationIds">The pending migration ids (timestamp-prefixed).</param>
/// <param name="ct">Cancellation.</param>
/// <returns>The findings.</returns>
internal static async Task<IReadOnlyList<PreflightFinding>> RunAsync(
SqlConnection connection, IReadOnlyCollection<string> pendingMigrationIds, CancellationToken ct)
{
var findings = new List<PreflightFinding>();
foreach (var migration in All.Select(c => c.Migration).Distinct())
{
var check = $"migration:{migration}";
if (!pendingMigrationIds.Any(id => id.EndsWith("_" + migration, StringComparison.Ordinal)))
{
findings.Add(new(check, "AlreadyApplied", PreflightSeverity.Info,
$"{migration} is already applied (or not part of this build); its pre-check is not needed."));
continue;
}
var clean = true;
foreach (var c in All.Where(c => c.Migration == migration))
{
List<(string Key, string Id)> rows;
try
{
rows = await QueryAsync(connection, c.Sql, ct).ConfigureAwait(false);
}
catch (SqlException ex)
{
clean = false;
findings.Add(new(check, c.Code, PreflightSeverity.Warning,
$"pre-check {c.Code} could not run against this schema ({OneLine(ex.Message)}); the migration's own pre-check will still refuse bad rows."));
continue;
}
foreach (var group in rows.GroupBy(r => r.Key, StringComparer.Ordinal))
{
clean = false;
var ids = group.Select(r => r.Id).ToList();
findings.Add(new(check, c.Code, PreflightSeverity.Blocking, c.Describe(group.Key, ids), ids.Count == 1 ? ids[0] : null));
}
}
if (clean)
findings.Add(new(check, "Clean", PreflightSeverity.Info, $"{migration} will apply: no row breaks its new constraints."));
}
return findings;
}
private static string OneLine(string message) =>
string.Join(" ", message.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Distinct(StringComparer.Ordinal));
private static async Task<List<(string Key, string Id)>> QueryAsync(SqlConnection connection, string sql, CancellationToken ct)
{
var rows = new List<(string, string)>();
await using var cmd = connection.CreateCommand();
cmd.CommandText = sql;
await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
while (await reader.ReadAsync(ct).ConfigureAwait(false))
rows.Add((reader.IsDBNull(0) ? string.Empty : reader.GetString(0), reader.IsDBNull(1) ? string.Empty : reader.GetString(1)));
return rows;
}
}
@@ -0,0 +1,55 @@
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight;
/// <summary>How much a preflight finding matters for the upgrade.</summary>
public enum PreflightSeverity
{
/// <summary>The upgrade (a migration) or the next deploy will be REFUSED until this is fixed.</summary>
Blocking,
/// <summary>Not refused, but worth fixing (behaviour change, or refused only in a non-default mode).</summary>
Warning,
/// <summary>Context only.</summary>
Info,
}
/// <summary>One preflight finding.</summary>
/// <param name="Check">Which check produced it (<c>schema</c>, <c>migration:&lt;name&gt;</c>, <c>deploy-gate</c>, <c>script-gate</c>).</param>
/// <param name="Code">The rule code — the deploy gate's own code for gate findings.</param>
/// <param name="Severity">How much it matters.</param>
/// <param name="Message">Operator-facing text naming the rows.</param>
/// <param name="Subject">The offending row's id, when there is one.</param>
public sealed record PreflightFinding(string Check, string Code, PreflightSeverity Severity, string Message, string? Subject = null);
/// <summary>The whole preflight result for one ConfigDb.</summary>
/// <param name="Server">The SQL Server data source (never the credentials).</param>
/// <param name="Database">The database name.</param>
/// <param name="AppliedMigrations">Migrations already applied, oldest first.</param>
/// <param name="PendingMigrations">Migrations this build would apply, oldest first.</param>
/// <param name="Findings">Every finding, in check order.</param>
public sealed record PreflightReport(
string Server,
string Database,
IReadOnlyList<string> AppliedMigrations,
IReadOnlyList<string> PendingMigrations,
IReadOnlyList<PreflightFinding> Findings)
{
/// <summary>True when any finding would refuse the upgrade or the next deploy.</summary>
public bool HasBlocking => Findings.Any(f => f.Severity == PreflightSeverity.Blocking);
}
/// <summary>Preflight knobs — set them as the target deployment's appsettings are.</summary>
public sealed record UpgradePreflightOptions
{
/// <summary><c>Deployment:TagConfigValidationMode</c> of the target (Warn is the shipped default).</summary>
public AdminOperations.TagConfigValidationMode TagConfigMode { get; init; } = AdminOperations.TagConfigValidationMode.Warn;
/// <summary><c>Deployment:ScriptCompileGateMode</c> of the target (Error is the shipped default).</summary>
public AdminOperations.ScriptCompileGateMode ScriptGateMode { get; init; } = AdminOperations.ScriptCompileGateMode.Error;
/// <summary>Also compile scripts no enabled VirtualTag / scripted alarm / Calculation tag uses (Warning only).</summary>
public bool CheckUnusedScripts { get; init; } = true;
}
/// <summary>The target is not something the preflight can check (not a v3 ConfigDb, unreachable).</summary>
public sealed class PreflightUnsupportedException(string message, Exception? inner = null) : Exception(message, inner);
@@ -0,0 +1,201 @@
using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight;
/// <summary>
/// The read-only pre-upgrade preflight (lmxopcua#1013, #1015, #1021, #1058): connects to a ConfigDb — normally
/// BEFORE this build's migrations are applied to it — and reports every row the upgrade would refuse:
/// <list type="number">
/// <item><b>Migration pre-checks</b> (<see cref="MigrationPreChecks"/>) — the rows each pending constraint-adding
/// migration would THROW on, named.</item>
/// <item><b>The deploy gate</b> — <see cref="DeployGateRules"/> (every <c>DraftValidator</c> rule incl. the new
/// VirtualTag name / effective-name / script-reference / ZTag / dangling-reference / Sql named-query rules, the
/// topology check, the TagConfig inspection) over the same whole-DB snapshot a deploy reads, through this build's
/// code. The first deploy after the upgrade is refused for every Blocking one.</item>
/// <item><b>The script compile gate</b> — <see cref="DeployScriptGate"/> through the supplied
/// <see cref="IDeployScriptChecker"/> (the Roslyn compile + sandbox allow-list the runtime runs); optionally
/// also every stored script nothing currently uses.</item>
/// </list>
/// Only SELECTs are issued. The snapshot is read under SNAPSHOT isolation when the database allows it (the deploy
/// path's own read), else READ COMMITTED.
/// </summary>
public static class UpgradePreflight
{
private const string V3InitialSuffix = "_V3Initial";
/// <summary>Runs every check against the ConfigDb at <paramref name="connectionString"/>.</summary>
/// <param name="connectionString">The ConfigDb connection string.</param>
/// <param name="scriptChecker">The compile checker (the Host's <c>RoslynDeployScriptChecker</c>); null skips the script gate.</param>
/// <param name="options">Mode knobs matching the target deployment.</param>
/// <param name="ct">Cancellation.</param>
/// <returns>The report.</returns>
/// <exception cref="PreflightUnsupportedException">The database is unreachable or not a v3 ConfigDb.</exception>
public static async Task<PreflightReport> RunAsync(
string connectionString, IDeployScriptChecker? scriptChecker, UpgradePreflightOptions? options = null, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(connectionString);
options ??= new UpgradePreflightOptions();
var csb = new SqlConnectionStringBuilder(connectionString);
var findings = new List<PreflightFinding>();
await using var connection = new SqlConnection(connectionString);
try
{
await connection.OpenAsync(ct).ConfigureAwait(false);
}
catch (SqlException ex)
{
throw new PreflightUnsupportedException($"cannot connect to '{csb.DataSource}' / '{csb.InitialCatalog}': {ex.Message}", ex);
}
var applied = await ReadAppliedMigrationsAsync(connection, ct).ConfigureAwait(false);
if (!applied.Any(id => id.EndsWith(V3InitialSuffix, StringComparison.Ordinal)))
throw new PreflightUnsupportedException(
$"'{connection.Database}' is not a v3 OtOpcUa ConfigDb (no {V3InitialSuffix[1..]} migration in __EFMigrationsHistory); " +
"this preflight checks an upgrade between v3 builds only.");
var plainOptions = new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(connectionString).Options;
IReadOnlyList<string> pending;
Microsoft.EntityFrameworkCore.Metadata.IModel model;
await using (var plain = new OtOpcUaConfigDbContext(plainOptions))
{
pending = plain.Database.GetMigrations().Except(applied, StringComparer.Ordinal).ToList();
model = plain.Model;
var unknown = applied.Except(plain.Database.GetMigrations(), StringComparer.Ordinal).ToList();
if (unknown.Count > 0)
findings.Add(new("schema", "UnknownMigrations", PreflightSeverity.Warning,
$"the database has migration(s) this build does not know ({string.Join(", ", unknown)}) — it is NEWER than this build; " +
"the checks below may not match what it will do."));
}
findings.Add(new("schema", "PendingMigrations", PreflightSeverity.Info, pending.Count == 0
? "no pending migrations — the schema is already this build's."
: $"{pending.Count} pending migration(s) this build would apply: {string.Join(", ", pending)}."));
// 1. Migration pre-checks (raw SQL against the current schema).
findings.AddRange(await MigrationPreChecks.RunAsync(connection, pending, ct).ConfigureAwait(false));
// 2 + 3. The deploy gate, on a snapshot read through this build's model, tolerant of an older schema.
var gaps = LegacySchemaTolerance.Compare(model, await ReadSchemaAsync(connection, ct).ConfigureAwait(false));
if (!gaps.IsEmpty)
findings.Add(new("schema", "ReadAsEmpty", PreflightSeverity.Info,
"tables / columns a pending migration creates are read as empty / default: " + gaps.Signature.Replace("|", " | ", StringComparison.Ordinal)));
DraftSnapshot draft;
try
{
draft = await ReadSnapshotAsync(connectionString, gaps, await SnapshotIsolationAllowedAsync(connection, ct).ConfigureAwait(false), findings, ct)
.ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
findings.Add(new("deploy-gate", "SnapshotUnreadable", PreflightSeverity.Blocking,
$"this build could not read the configuration snapshot ({ex.GetType().Name}: {ex.Message}) — the deploy would fail the same way. " +
"Fix the migration pre-check findings above (a NULL Script.ScriptId is one cause) and re-run."));
return new PreflightReport(csb.DataSource, connection.Database, applied, pending, findings);
}
var gate = DeployGateRules.Evaluate(draft, options.TagConfigMode);
findings.AddRange(gate.Errors.Select(e => new PreflightFinding("deploy-gate", e.Code, PreflightSeverity.Blocking, e.Message, e.Context)));
findings.AddRange(gate.TagConfigWarnings.Select(e => new PreflightFinding("deploy-gate", e.Code, PreflightSeverity.Warning,
e.Message + " (blocking only with Deployment:TagConfigValidationMode=Error)", e.Context)));
findings.AddRange(gate.SqlWritableWarnings.Select(w => new PreflightFinding("deploy-gate", "SqlWritableMismatch", PreflightSeverity.Warning, w)));
findings.AddRange(gate.DataConnectionWarnings.Select(w => new PreflightFinding("deploy-gate", "DataConnectionWarning", PreflightSeverity.Warning, w)));
if (gate.Errors.Count == 0)
findings.Add(new("deploy-gate", "Clean", PreflightSeverity.Info, "every deploy-gate rule passes."));
RunScriptGate(scriptChecker, draft, options, findings, ct);
return new PreflightReport(csb.DataSource, connection.Database, applied, pending, findings);
}
private static void RunScriptGate(
IDeployScriptChecker? checker, DraftSnapshot draft, UpgradePreflightOptions options, List<PreflightFinding> findings, CancellationToken ct)
{
if (checker is null || options.ScriptGateMode == ScriptCompileGateMode.Off)
{
findings.Add(new("script-gate", "Skipped", PreflightSeverity.Info, "script compile gate not run."));
return;
}
var severity = options.ScriptGateMode == ScriptCompileGateMode.Error ? PreflightSeverity.Blocking : PreflightSeverity.Warning;
var refused = DeployScriptGate.Run(checker, draft, ct);
findings.AddRange(refused.Select(f => new PreflightFinding("script-gate", DeployScriptGate.ErrorCode, severity, f.Text, f.ScriptId)));
var used = DeployScriptGate.CollectUses(draft).Select(u => u.ScriptId).ToHashSet(StringComparer.Ordinal);
var unused = draft.Scripts.Where(s => !used.Contains(s.ScriptId)).OrderBy(s => s.ScriptId, StringComparer.Ordinal).ToList();
if (options.CheckUnusedScripts && unused.Count > 0)
{
// Nothing compiles these today, so they block nothing — but binding one to a VirtualTag / alarm later is
// refused at that deploy. Checked as a value script (the seam a VirtualTag or Calculation tag compiles for).
var results = checker.Check(unused.Select(s => new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, s.SourceCode ?? string.Empty)).ToList(), ct);
for (var i = 0; i < unused.Count; i++)
if (!results[i].Passed)
findings.Add(new("script-gate", "UnusedScriptDoesNotCompile", PreflightSeverity.Warning,
$"script '{unused[i].ScriptId}' ('{unused[i].Name}') is not used by any enabled VirtualTag, scripted alarm or Calculation tag, " +
$"and would not compile as a value script: {string.Join("; ", results[i].Problems)}",
unused[i].ScriptId));
}
findings.Add(new("script-gate", refused.Count == 0 ? "Clean" : "Summary", PreflightSeverity.Info,
$"{used.Count} script(s) in use checked, {refused.Count} refused" +
(options.CheckUnusedScripts ? $"; {unused.Count} unused script(s) checked." : ".")));
}
private static async Task<DraftSnapshot> ReadSnapshotAsync(
string connectionString, LegacySchemaTolerance.SchemaGaps gaps, bool snapshotAllowed, List<PreflightFinding> findings, CancellationToken ct)
{
var builder = new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(connectionString);
LegacySchemaTolerance.Apply(builder, gaps);
await using var db = new OtOpcUaConfigDbContext(builder.Options);
if (snapshotAllowed) return await DraftSnapshotFactory.FromConfigDbAsync(db, ct).ConfigureAwait(false);
findings.Add(new("schema", "NoSnapshotIsolation", PreflightSeverity.Warning,
"ALLOW_SNAPSHOT_ISOLATION is OFF (migration EnableSnapshotIsolation not applied?) — read under READ COMMITTED, so an edit " +
"committed mid-read could show as a transient finding; re-run to confirm. The deploy itself requires snapshot isolation."));
await using var tx = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct).ConfigureAwait(false);
var draft = await DraftSnapshotFactory.FromConfigDbAsync(db, ct).ConfigureAwait(false);
await tx.RollbackAsync(ct).ConfigureAwait(false);
return draft;
}
private static async Task<List<string>> ReadAppliedMigrationsAsync(SqlConnection connection, CancellationToken ct)
{
await using var cmd = connection.CreateCommand();
cmd.CommandText = "IF OBJECT_ID(N'[__EFMigrationsHistory]', N'U') IS NOT NULL SELECT MigrationId FROM [__EFMigrationsHistory] ORDER BY MigrationId";
var ids = new List<string>();
await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
while (await reader.ReadAsync(ct).ConfigureAwait(false)) ids.Add(reader.GetString(0));
return ids;
}
private static async Task<Dictionary<string, HashSet<string>>> ReadSchemaAsync(SqlConnection connection, CancellationToken ct)
{
await using var cmd = connection.CreateCommand();
cmd.CommandText = "SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = N'dbo'";
var schema = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);
await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
while (await reader.ReadAsync(ct).ConfigureAwait(false))
{
var table = reader.GetString(0);
if (!schema.TryGetValue(table, out var columns))
schema[table] = columns = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
columns.Add(reader.GetString(1));
}
return schema;
}
private static async Task<bool> SnapshotIsolationAllowedAsync(SqlConnection connection, CancellationToken ct)
{
await using var cmd = connection.CreateCommand();
cmd.CommandText = "SELECT snapshot_isolation_state FROM sys.databases WHERE name = DB_NAME()";
return await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false) is byte state && state == 1;
}
}
@@ -958,7 +958,7 @@ public static class AddressSpaceComposer
if (!equipFolderPath.TryGetValue(r.EquipmentId, out var equipPath)) continue;
var rawPath = topology.Resolver.TryBuildTagPath(tag.DeviceId, tag.TagGroupId, tag.Name);
if (rawPath is null) continue;
var effectiveName = string.IsNullOrEmpty(r.DisplayNameOverride) ? tag.Name : r.DisplayNameOverride!;
var effectiveName = EquipmentReferenceMap.EffectiveName(r.DisplayNameOverride, tag.Name)!;
string nodeId;
try
@@ -217,8 +217,7 @@ public sealed partial class LocalExportCatalog
|| !equipmentById.TryGetValue(reference.EquipmentId, out var owner)
|| !lineById.TryGetValue(owner.UnsLineId, out var line) || !areaById.TryGetValue(line.UnsAreaId, out var area))
continue;
var effectiveName = string.IsNullOrEmpty(reference.DisplayNameOverride) ? tagById[reference.TagId].Name
: reference.DisplayNameOverride!;
var effectiveName = EquipmentReferenceMap.EffectiveName(reference.DisplayNameOverride, tagById[reference.TagId].Name)!;
string reserved;
try { reserved = V3NodeIds.UnsChild(V3NodeIds.Uns(area.Name, line.Name, owner.Name), effectiveName); }
catch (ArgumentException) { continue; } // an invalid name segment: the deploy gate rejects it; never listed
@@ -1240,9 +1240,8 @@ internal sealed partial class ParsedDeploymentArtifact : IDisposable
// Effective name = the override when present, else the backing raw tag's own name. This is the
// same rule the address space materializes UNS variables under; a reference whose tag is
// missing from the artifact has no resolvable name and is skipped.
var effective = ReadNullableString(el, "DisplayNameOverride");
if (string.IsNullOrWhiteSpace(effective))
effective = tags.TryGetValue(tagId, out var t) ? t.Name : null;
var effective = EquipmentReferenceMap.EffectiveName(
ReadNullableString(el, "DisplayNameOverride"), tags.TryGetValue(tagId, out var t) ? t.Name : null);
if (effective is null) continue;
references.Add((equipmentId, tagId, effective));