Group all 69 projects into category subfolders under src/ and tests/ so the Rider Solution Explorer mirrors the module structure. Folders: Core, Server, Drivers (with a nested Driver CLIs subfolder), Client, Tooling. - Move every project folder on disk with git mv (history preserved as renames). - Recompute relative paths in 57 .csproj files: cross-category ProjectReferences, the lib/ HintPath+None refs in Driver.Historian.Wonderware, and the external mxaccessgw refs in Driver.Galaxy and its test project. - Rebuild ZB.MOM.WW.OtOpcUa.slnx with nested solution folders. - Re-prefix project paths in functional scripts (e2e, compliance, smoke SQL, integration, install). Build green (0 errors); unit tests pass. Docs left for a separate pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
239 lines
11 KiB
C#
239 lines
11 KiB
C#
using System.Text.RegularExpressions;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
|
|
|
/// <summary>
|
|
/// Managed-code pre-publish validator per decision #91. Complements the structural checks in
|
|
/// <c>sp_ValidateDraft</c> — this layer owns schema validation for JSON columns, UNS segment
|
|
/// regex, EquipmentId derivation, cross-cluster checks, and anything else that's uncomfortable
|
|
/// to express in T-SQL. Returns every failing rule in one pass (decision: surface all errors,
|
|
/// not just the first, so operators fix in bulk).
|
|
/// </summary>
|
|
public static class DraftValidator
|
|
{
|
|
private static readonly Regex UnsSegment = new(@"^[a-z0-9-]{1,32}$", RegexOptions.Compiled);
|
|
private const string UnsDefaultSegment = "_default";
|
|
private const int MaxPathLength = 200;
|
|
|
|
public static IReadOnlyList<ValidationError> Validate(DraftSnapshot draft)
|
|
{
|
|
var errors = new List<ValidationError>();
|
|
|
|
ValidateUnsSegments(draft, errors);
|
|
ValidatePathLength(draft, errors);
|
|
ValidateEquipmentUuidImmutability(draft, errors);
|
|
ValidateSameClusterNamespaceBinding(draft, errors);
|
|
ValidateReservationPreflight(draft, errors);
|
|
ValidateEquipmentIdDerivation(draft, errors);
|
|
ValidateDriverNamespaceCompatibility(draft, errors);
|
|
|
|
return errors;
|
|
}
|
|
|
|
private static bool IsValidSegment(string? s) =>
|
|
s is not null && (UnsSegment.IsMatch(s) || s == UnsDefaultSegment);
|
|
|
|
private static void ValidateUnsSegments(DraftSnapshot draft, List<ValidationError> errors)
|
|
{
|
|
foreach (var a in draft.UnsAreas)
|
|
if (!IsValidSegment(a.Name))
|
|
errors.Add(new("UnsSegmentInvalid",
|
|
$"UnsArea.Name '{a.Name}' does not match [a-z0-9-]{{1,32}} or '_default'",
|
|
a.UnsAreaId));
|
|
|
|
foreach (var l in draft.UnsLines)
|
|
if (!IsValidSegment(l.Name))
|
|
errors.Add(new("UnsSegmentInvalid",
|
|
$"UnsLine.Name '{l.Name}' does not match [a-z0-9-]{{1,32}} or '_default'",
|
|
l.UnsLineId));
|
|
|
|
foreach (var e in draft.Equipment)
|
|
if (!IsValidSegment(e.Name))
|
|
errors.Add(new("UnsSegmentInvalid",
|
|
$"Equipment.Name '{e.Name}' does not match [a-z0-9-]{{1,32}} or '_default'",
|
|
e.EquipmentId));
|
|
}
|
|
|
|
/// <summary>Cluster.Enterprise + Site + area + line + equipment + 4 slashes ≤ 200 chars.</summary>
|
|
private static void ValidatePathLength(DraftSnapshot draft, List<ValidationError> errors)
|
|
{
|
|
// The cluster row isn't in the snapshot — we assume caller pre-validated Enterprise+Site
|
|
// length and bound them as constants <= 64 chars each. Here we validate the dynamic portion.
|
|
var areaById = draft.UnsAreas.ToDictionary(a => a.UnsAreaId);
|
|
var lineById = draft.UnsLines.ToDictionary(l => l.UnsLineId);
|
|
|
|
foreach (var eq in draft.Equipment.Where(e => e.UnsLineId is not null))
|
|
{
|
|
if (!lineById.TryGetValue(eq.UnsLineId!, out var line)) continue;
|
|
if (!areaById.TryGetValue(line.UnsAreaId, out var area)) continue;
|
|
|
|
// rough upper bound: Enterprise+Site at most 32+32; add dynamic segments + 4 slashes
|
|
var len = 32 + 32 + area.Name.Length + line.Name.Length + eq.Name.Length + 4;
|
|
if (len > MaxPathLength)
|
|
errors.Add(new("PathTooLong",
|
|
$"Equipment path exceeds {MaxPathLength} chars (approx {len})",
|
|
eq.EquipmentId));
|
|
}
|
|
}
|
|
|
|
private static void ValidateEquipmentUuidImmutability(DraftSnapshot draft, List<ValidationError> errors)
|
|
{
|
|
var priorById = draft.PriorEquipment
|
|
.GroupBy(e => e.EquipmentId)
|
|
.ToDictionary(g => g.Key, g => g.First().EquipmentUuid);
|
|
|
|
foreach (var eq in draft.Equipment)
|
|
{
|
|
if (priorById.TryGetValue(eq.EquipmentId, out var priorUuid) && priorUuid != eq.EquipmentUuid)
|
|
errors.Add(new("EquipmentUuidImmutable",
|
|
$"EquipmentId '{eq.EquipmentId}' had UUID '{priorUuid}' in a prior generation; cannot change to '{eq.EquipmentUuid}'",
|
|
eq.EquipmentId));
|
|
}
|
|
}
|
|
|
|
private static void ValidateSameClusterNamespaceBinding(DraftSnapshot draft, List<ValidationError> errors)
|
|
{
|
|
var nsById = draft.Namespaces.ToDictionary(n => n.NamespaceId);
|
|
|
|
foreach (var di in draft.DriverInstances)
|
|
{
|
|
if (!nsById.TryGetValue(di.NamespaceId, out var ns))
|
|
{
|
|
errors.Add(new("NamespaceUnresolved",
|
|
$"DriverInstance '{di.DriverInstanceId}' references unknown NamespaceId '{di.NamespaceId}'",
|
|
di.DriverInstanceId));
|
|
continue;
|
|
}
|
|
|
|
if (ns.ClusterId != di.ClusterId)
|
|
errors.Add(new("BadCrossClusterNamespaceBinding",
|
|
$"DriverInstance '{di.DriverInstanceId}' is in cluster '{di.ClusterId}' but references namespace in cluster '{ns.ClusterId}'",
|
|
di.DriverInstanceId));
|
|
}
|
|
}
|
|
|
|
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>Decision #125: EquipmentId = 'EQ-' + lowercase first 12 hex chars of the UUID.</summary>
|
|
public static string DeriveEquipmentId(Guid uuid) =>
|
|
"EQ-" + uuid.ToString("N")[..12].ToLowerInvariant();
|
|
|
|
private static void ValidateEquipmentIdDerivation(DraftSnapshot draft, List<ValidationError> errors)
|
|
{
|
|
foreach (var eq in draft.Equipment)
|
|
{
|
|
var expected = DeriveEquipmentId(eq.EquipmentUuid);
|
|
if (!string.Equals(eq.EquipmentId, expected, StringComparison.Ordinal))
|
|
errors.Add(new("EquipmentIdNotDerived",
|
|
$"Equipment.EquipmentId '{eq.EquipmentId}' does not match the canonical derivation '{expected}'",
|
|
eq.EquipmentId));
|
|
}
|
|
}
|
|
|
|
private static void ValidateDriverNamespaceCompatibility(DraftSnapshot draft, List<ValidationError> errors)
|
|
{
|
|
var nsById = draft.Namespaces.ToDictionary(n => n.NamespaceId);
|
|
|
|
foreach (var di in draft.DriverInstances)
|
|
{
|
|
if (!nsById.TryGetValue(di.NamespaceId, out var ns)) continue;
|
|
|
|
var compat = ns.Kind switch
|
|
{
|
|
NamespaceKind.SystemPlatform => di.DriverType == "Galaxy",
|
|
NamespaceKind.Equipment => di.DriverType != "Galaxy",
|
|
_ => true,
|
|
};
|
|
|
|
if (!compat)
|
|
errors.Add(new("DriverNamespaceKindMismatch",
|
|
$"DriverInstance '{di.DriverInstanceId}' ({di.DriverType}) is not allowed in {ns.Kind} namespace",
|
|
di.DriverInstanceId));
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Phase 6.3 Stream A.2 + task #148 part 2 — managed pre-publish guard for cluster
|
|
/// topology vs. <see cref="ServerCluster.RedundancyMode"/>. The SQL
|
|
/// <c>CK_ServerCluster_RedundancyMode_NodeCount</c> CHECK already enforces the
|
|
/// (NodeCount, RedundancyMode) pair on the row itself, but it cannot see the
|
|
/// <see cref="ClusterNode.Enabled"/> flag on child nodes — an operator can toggle
|
|
/// nodes off (effective count = 1) while leaving RedundancyMode at Hot and the
|
|
/// constraint stays green. This check catches that drift before publish so the
|
|
/// runtime doesn't boot into a topology the <see cref="Enums.RedundancyMode"/> claims
|
|
/// is invalid.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Called from the publish pipeline separately from <see cref="Validate"/> because the
|
|
/// cluster/nodes rows aren't generation-versioned — they don't belong on
|
|
/// <see cref="DraftSnapshot"/>. Returns every failing rule in one pass, same shape as
|
|
/// <see cref="Validate"/>.
|
|
/// </remarks>
|
|
public static IReadOnlyList<ValidationError> ValidateClusterTopology(
|
|
ServerCluster cluster,
|
|
IReadOnlyList<ClusterNode> clusterNodes)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(cluster);
|
|
ArgumentNullException.ThrowIfNull(clusterNodes);
|
|
|
|
var errors = new List<ValidationError>();
|
|
var enabledNodes = clusterNodes.Count(n => n.Enabled);
|
|
|
|
// Declared count must match declared mode (belt around the SQL CHECK).
|
|
var declaredOk = (cluster.NodeCount, cluster.RedundancyMode) switch
|
|
{
|
|
(1, RedundancyMode.None) => true,
|
|
(2, RedundancyMode.Warm) => true,
|
|
(2, RedundancyMode.Hot) => true,
|
|
_ => false,
|
|
};
|
|
if (!declaredOk)
|
|
errors.Add(new("ClusterRedundancyModeInvalid",
|
|
$"Cluster '{cluster.ClusterId}' declares NodeCount={cluster.NodeCount} + RedundancyMode={cluster.RedundancyMode}. " +
|
|
$"Supported combinations: (1, None), (2, Warm), (2, Hot).",
|
|
cluster.ClusterId));
|
|
|
|
// Enabled-node count must match declared count. Disabling a node to 1 while leaving
|
|
// mode at Hot/Warm would boot the runtime into InvalidTopology band.
|
|
if (enabledNodes != cluster.NodeCount)
|
|
errors.Add(new("ClusterEnabledNodeCountMismatch",
|
|
$"Cluster '{cluster.ClusterId}' declares NodeCount={cluster.NodeCount} but has {enabledNodes} Enabled nodes. " +
|
|
$"Toggle the missing node(s) back on or change RedundancyMode/NodeCount to match.",
|
|
cluster.ClusterId));
|
|
|
|
// Primary uniqueness — decision #84. Two Primary nodes is always an invariant violation
|
|
// regardless of mode; catch it here so publish fails loud rather than the runtime
|
|
// demoting both to ServiceLevelBand.InvalidTopology at boot.
|
|
var primaryCount = clusterNodes.Count(n => n.Enabled && n.RedundancyRole == RedundancyRole.Primary);
|
|
if (primaryCount > 1)
|
|
errors.Add(new("ClusterMultiplePrimary",
|
|
$"Cluster '{cluster.ClusterId}' has {primaryCount} Enabled Primary nodes. At most one Primary per cluster.",
|
|
cluster.ClusterId));
|
|
|
|
return errors;
|
|
}
|
|
}
|