Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/DeployGateRules.cs
T
Joseph Doherty 6cffffe673 feat(tooling): #1013 #1015 #1021 #1058 read-only upgrade preflight (otopcua-preflight)
One command, run from the NEW build against a ConfigDb BEFORE its migrations, that names every row
the upgrade or the next deploy would refuse; exit 1 if any, 2 if unreachable / not v3.
- migration:* — row-naming twins of the constraint-adding migrations' pre-checks
  (ConfigurationGapsIndexesAndRowVersions: duplicate NodeAcl / LdapGroupRoleMapping;
  ScriptForeignKeysAndExternalIdUniqueness: NULL ScriptId, dangling VT/alarm scripts, duplicate
  ZTag/SAPID, reservation rows). (#1021)
- deploy-gate — DeployGateRules, the gate's rule pass now extracted from AdminOperationsActor so
  both run the same code: every DraftValidator rule incl. VirtualTagNameInvalid /
  UnsEffectiveNameInvalid / *ScriptNotFound (#1015) and SqlNamedQueryInvalid (#1058), topology,
  TagConfig inspection.
- script-gate — DeployScriptGate through RoslynDeployScriptChecker, plus every unused stored
  script (Warning). (#1013)
An older schema is read through this build's model: tables a pending migration creates map to a
typed zero-row query, added columns are left out of the model (LegacySchemaTolerance). SNAPSHOT
read when allowed. Logic in ControlPlane/Preflight (Roslyn-free); the console shell binds Roslyn.
Real-SQL tests: an old-schema DB with every finding class (and nothing written), clean controls,
NULL ScriptId -> SnapshotUnreadable, non-v3 refused. docs/v2/upgrade-preflight.md records the dev
runs; production runs stay user-gated (wonder-box hold).
2026-12-03 15:41:30 -05:00

86 lines
5.1 KiB
C#

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));
}
}