Files
lmxopcua/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs
T
Joseph Doherty ac9455634d feat(grpc-data): A2a AddDataConnectionConditions schema; authoring accepts AlarmSubscribe
Migration per plan 6: DataExport.MaxConditions (1000), AllowGalaxyServiceAck (false); RemoteNamespaceMapping.MaxConditions
(1000), ConditionStaleTimeoutMilliseconds (30000), ConditionMethodTimeoutMilliseconds (5000),
ConditionSnapshotTimeoutMilliseconds (30000); NOT NULL with SQL defaults, check constraints widened. Validator known set
grows by AlarmSubscribe (method bits stay rejected); condition limits bounded (MaxConditions <= 5000 = the node manager's
per-hold clamp, timeouts <= 1 h); AllowGalaxyServiceAck only with AlarmAcknowledge; non-blocking
ConditionCapacityWarnings when a consumer node's alarm mappings' MaxConditions x 49 exceed MaxImportedConditionNodes.
2026-11-24 12:05:09 -05:00

363 lines
28 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Text.RegularExpressions;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation;
/// <summary>Validates deployed data-service configuration without resolving consumer-side secrets.</summary>
public static class DataConnectionValidator
{
/// <summary>
/// The operations AUTHORING may grant. It grows only in the phase that implements a bit, so authoring cannot get ahead
/// of the code (plan section 4.3, "grow site"): H2 added <see cref="DataOperations.HistoryRead"/> together with
/// <see cref="DataOperationSets.Understood"/> and the origin's <c>Implemented(target)</c>; A2a adds
/// <see cref="DataOperations.AlarmSubscribe"/>; A2b adds the method bits (acknowledge/confirm/shelve).
/// </summary>
private const DataOperations KnownOperations = DataOperationSets.V1 | DataOperations.HistoryRead | DataOperations.AlarmSubscribe;
private static readonly StringComparer Ids = StringComparer.OrdinalIgnoreCase;
// H2 upper bounds: keep derived capacities (sessions x reads x batch, remainder budgets) far from int overflow.
/// <summary>Largest <c>DataConnection.HistoryTimeoutMilliseconds</c> (1 h).</summary>
public const int MaxHistoryTimeoutMilliseconds = 3_600_000;
/// <summary>Largest <c>DataExport.MaxConcurrentHistoryReads</c>.</summary>
public const int MaxConcurrentHistoryReadsLimit = 64;
/// <summary>Largest <c>DataExport.MaxHistoryValuesPerPage</c>.</summary>
public const int MaxHistoryValuesPerPageLimit = 1_000_000;
/// <summary>Largest <c>DataExport.MaxHistoryResponseBytes</c> (64 MiB).</summary>
public const int MaxHistoryResponseBytesLimit = 64 * 1024 * 1024;
/// <summary>Smallest <c>DataExport.MaxHistoryResponseBytes</c> (256 KiB): below it a page of ordinary values cannot fit.</summary>
public const int MinHistoryResponseBytesLimit = 256 * 1024;
/// <summary>Largest <c>RemoteNamespaceMapping.MaxHistoryAssemblyBytesPerRequest</c> (1 GiB).</summary>
public const int MaxHistoryAssemblyBytesLimit = 1024 * 1024 * 1024;
// A2 bounds (plan §5.5/§6).
/// <summary>
/// Largest <c>DataExport.MaxConditions</c> / <c>RemoteNamespaceMapping.MaxConditions</c>: the node manager snapshots at most
/// this many conditions under one <c>Lock</c> hold (<c>OtOpcUaNodeManager.MaxConditionsPerHoldLimit</c>, which this mirrors).
/// </summary>
public const int MaxConditionsLimit = 5000;
/// <summary>Largest condition stale / method / snapshot timeout (1 h), like <see cref="MaxHistoryTimeoutMilliseconds"/>.</summary>
public const int MaxConditionTimeoutMilliseconds = 3_600_000;
/// <summary>Worst-case nodes one imported condition materialises (plan §5.5: 48–49 counted nodes).</summary>
public const int NodesPerImportedCondition = 49;
/// <summary>Default of the host option <c>DataConnections:MaxImportedConditionNodes</c> (= 2,500 × 49) per consumer node.</summary>
public const int DefaultMaxImportedConditionNodes = 122_500;
/// <summary>Authoring/deploy-gate validation: an operation bit outside the known set is an error.</summary>
public static IReadOnlyList<ValidationError> Validate(DraftSnapshot draft) => Validate(draft, deployed: false);
/// <summary>
/// Node-side re-validation of an already-deployed artifact (artifact parse, origin catalog compile). Identical to
/// <see cref="Validate(DraftSnapshot)"/> except that operation bits outside <see cref="DataOperationSets.Understood"/>
/// are IGNORED rather than rejected (X0 tolerant reader): a newer central may author them, and rejecting would take
/// down every data connection/export on the node. The understood subset is still validated (a mapping may not grant
/// an understood operation its connection lacks), and every consumer of the rows masks the rest away, so an unknown bit
/// grants nothing (fail closed). A row must carry SOME bit (zero is still invalid), but it may carry only unknown
/// bits: such a row is kept and grants nothing.
/// </summary>
public static IReadOnlyList<ValidationError> ValidateDeployed(DraftSnapshot draft) => Validate(draft, deployed: true);
private static IReadOnlyList<ValidationError> Validate(DraftSnapshot draft, bool deployed)
{
ArgumentNullException.ThrowIfNull(draft);
var errors = new List<ValidationError>();
void Add(string code, string id, string message) => errors.Add(new(code, message, id));
bool Same(string? a, string? b) => Ids.Equals(a, b);
bool ValidOps(DataOperations operations) => operations != DataOperations.None &&
(deployed || (operations & ~KnownOperations) == 0);
DataOperations Understood(DataOperations operations) => deployed ? operations & DataOperationSets.Understood : operations;
bool NodesValid(IEnumerable<string> ids, string owner)
{
var list = ids.ToList();
return list.Count > 0 && list.All(x => !string.IsNullOrWhiteSpace(x)) &&
list.Distinct(Ids).Count() == list.Count && list.All(id => draft.ClusterNodes.Any(n =>
Same(n.NodeId, id) && Same(n.ClusterId, owner) && n.Enabled));
}
static bool ConditionTimeout(int milliseconds) => milliseconds > 0 && milliseconds <= MaxConditionTimeoutMilliseconds;
bool ValidSegment(string? value, DataRealm realm) => realm == DataRealm.Uns
? UnsSegment.IsValid(value)
: value is not null && value.Length <= 128 && RawPaths.ValidateSegment(value) is null;
bool ValidEndpoint(string endpoint) => Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) &&
uri.Scheme == Uri.UriSchemeHttps && string.IsNullOrEmpty(uri.UserInfo) &&
string.IsNullOrEmpty(uri.Query) && string.IsNullOrEmpty(uri.Fragment);
bool ValidSecretReference(string? reference) => reference is not null &&
Regex.IsMatch(reference, @"\Asecret:data/[a-z0-9][a-z0-9._/-]*\z", RegexOptions.CultureInvariant) &&
!reference.Contains("..", StringComparison.Ordinal);
void DuplicateIds(IEnumerable<string> ids, string kind)
{
foreach (var duplicate in ids.Where(id => !string.IsNullOrWhiteSpace(id))
.GroupBy(id => id, Ids).Where(group => group.Count() > 1))
{
Add("DataLogicalIdDuplicate", duplicate.Key, $"Duplicate {kind} logical ID.");
}
}
DuplicateIds(draft.DataConnections.Select(x => x.DataConnectionId), "connection");
DuplicateIds(draft.DataExports.Select(x => x.DataExportId), "export");
DuplicateIds(draft.RemoteNamespaceMappings.Select(x => x.RemoteNamespaceMappingId), "mapping");
foreach (var connection in draft.DataConnections)
{
var id = connection.DataConnectionId;
if ((connection.Enabled && connection.Endpoints.Count == 0) ||
connection.Endpoints.Any(endpoint => !string.IsNullOrWhiteSpace(endpoint) ? !ValidEndpoint(endpoint) : connection.Enabled))
{
Add("DataConnectionEndpointInvalid", id, "Endpoints must be absolute HTTPS URIs without credentials, query or fragment.");
}
if ((connection.Enabled || !string.IsNullOrWhiteSpace(connection.SecretReference)) &&
(!ValidSecretReference(connection.SecretReference) ||
((connection.Enabled || !string.IsNullOrWhiteSpace(connection.SecretScopeClusterId)) &&
!Same(connection.SecretScopeClusterId, connection.ClusterId))))
{
Add("DataConnectionSecretReferenceInvalid", id, "A cluster-scoped data secret reference is required.");
}
}
foreach (var connection in draft.DataConnections.Where(x => x.Enabled))
{
var id = connection.DataConnectionId;
if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(connection.ClusterId) || connection.Revision <= 0 ||
string.IsNullOrWhiteSpace(connection.ExpectedClusterId) || !Enum.IsDefined(connection.TargetMode) ||
connection.TargetMode == DataTargetMode.Unspecified || !Enum.IsDefined(connection.Consistency) ||
connection.Consistency == DataConsistency.Unspecified)
Add("DataConnectionIdentityInvalid", id, "Connection identity, target mode and consistency are required.");
if (!NodesValid(connection.ConsumerNodeIds, connection.ClusterId))
Add("DataConnectionConsumerScopeInvalid", id, "Consumers must be distinct enabled nodes owned by the connection cluster.");
if (connection.TargetMode == DataTargetMode.Node)
{
if (string.IsNullOrWhiteSpace(connection.ExpectedNodeId) || connection.EligibleTargetNodeIds.Count != 0)
Add("DataConnectionTargetInvalid", id, "Node targets require one expected node and no cluster target set.");
if (Same(connection.ClusterId, connection.ExpectedClusterId) &&
connection.ConsumerNodeIds.Any(n => Same(n, connection.ExpectedNodeId)))
Add("DataConnectionSelfRoute", id, "A consumer cannot target itself.");
if (Same(connection.ClusterId, connection.ExpectedClusterId) && !draft.ClusterNodes.Any(n =>
Same(n.ClusterId, connection.ClusterId) && Same(n.NodeId, connection.ExpectedNodeId)))
Add("DataConnectionTargetInvalid", id, "Same-cluster target node must exist in the declared cluster.");
}
else if (connection.TargetMode == DataTargetMode.Cluster)
{
if (connection.ExpectedNodeId is not null || connection.EligibleTargetNodeIds.Count == 0 ||
connection.EligibleTargetNodeIds.Any(string.IsNullOrWhiteSpace) ||
connection.EligibleTargetNodeIds.Distinct(Ids).Count() != connection.EligibleTargetNodeIds.Count)
Add("DataConnectionTargetInvalid", id, "Cluster targets require a distinct nonempty eligible node set.");
if (Same(connection.ClusterId, connection.ExpectedClusterId) && connection.ConsumerNodeIds.Any(consumer =>
!connection.EligibleTargetNodeIds.Any(target => !Same(target, consumer))))
Add("DataConnectionSelfRoute", id, "Each consumer requires an eligible nonself target.");
if (Same(connection.ClusterId, connection.ExpectedClusterId) && connection.EligibleTargetNodeIds.Any(target =>
!draft.ClusterNodes.Any(n => Same(n.ClusterId, connection.ClusterId) && Same(n.NodeId, target) && n.Enabled && !n.MaintenanceMode)))
Add("DataConnectionTargetInvalid", id, "Same-cluster eligible targets must be enabled and out of maintenance.");
}
if (!ValidOps(connection.AllowedOperations))
Add("DataConnectionOperationsInvalid", id, "Connection operations must be a supported nonempty subset.");
if (connection.TimeoutMilliseconds <= 0 || connection.MaxBatchItems <= 0 || connection.MaxPageItems <= 0 ||
connection.MaxMessageBytes <= 0 || connection.MaxStreams <= 0 || connection.MaxMonitoredItems <= 0 || connection.MaxPendingBytes <= 0 ||
connection.HistoryTimeoutMilliseconds <= 0 || connection.HistoryTimeoutMilliseconds > MaxHistoryTimeoutMilliseconds)
Add("DataConnectionLimitInvalid", id, "Connection limits must be positive.");
}
// Resolve local entity ownership through existing trees. Projected mappings are never valid parents or exports.
string? Owner(string kind, string entityId) => kind switch
{
"Cluster" => draft.ServerClusters.FirstOrDefault(x => Same(x.ClusterId, entityId))?.ClusterId,
"RawFolder" => draft.RawFolders.FirstOrDefault(x => Same(x.RawFolderId, entityId))?.ClusterId,
"RawDriver" => draft.DriverInstances.FirstOrDefault(x => Same(x.DriverInstanceId, entityId))?.ClusterId,
"RawDevice" => DeviceOwner(entityId),
"RawTagGroup" => draft.TagGroups.FirstOrDefault(x => Same(x.TagGroupId, entityId)) is { } group ? DeviceOwner(group.DeviceId) : null,
"RawTag" => draft.Tags.FirstOrDefault(x => Same(x.TagId, entityId)) is { } tag ? DeviceOwner(tag.DeviceId) : null,
"UnsArea" => draft.UnsAreas.FirstOrDefault(x => Same(x.UnsAreaId, entityId))?.ClusterId,
"UnsLine" => LineOwner(entityId),
"Equipment" => draft.Equipment.FirstOrDefault(x => Same(x.EquipmentId, entityId)) is { } equipment ? LineOwner(equipment.UnsLineId) : null,
"UnsTagReference" => draft.UnsTagReferences.FirstOrDefault(x => Same(x.UnsTagReferenceId, entityId)) is { } reference ? EquipmentOwner(reference.EquipmentId) : null,
"VirtualTag" => draft.VirtualTags.FirstOrDefault(x => Same(x.VirtualTagId, entityId)) is { } virtualTag ? EquipmentOwner(virtualTag.EquipmentId) : null,
_ => null
};
string? DeviceOwner(string deviceId)
{
var device = draft.Devices.FirstOrDefault(x => Same(x.DeviceId, deviceId));
return device is null ? null : draft.DriverInstances.FirstOrDefault(x => Same(x.DriverInstanceId, device.DriverInstanceId))?.ClusterId;
}
string? EquipmentOwner(string equipmentId)
{
var equipment = draft.Equipment.FirstOrDefault(x => Same(x.EquipmentId, equipmentId));
return equipment is null ? null : LineOwner(equipment.UnsLineId);
}
string? LineOwner(string lineId)
{
var line = draft.UnsLines.FirstOrDefault(x => Same(x.UnsLineId, lineId));
return line is null ? null : draft.UnsAreas.FirstOrDefault(x => Same(x.UnsAreaId, line.UnsAreaId))?.ClusterId;
}
bool KindInRealm(string kind, DataRealm realm) => kind == "Cluster" || (realm switch
{
DataRealm.Raw => kind is "RawFolder" or "RawDriver" or "RawDevice" or "RawTagGroup" or "RawTag",
DataRealm.Uns => kind is "UnsArea" or "UnsLine" or "Equipment" or "UnsTagReference" or "VirtualTag",
_ => false
});
bool LocalCollision(RemoteNamespaceMapping m)
{
var name = m.BranchName;
bool Name(string? candidate) => string.Equals(candidate, name, StringComparison.Ordinal);
return m.LocalParentKind switch
{
"Cluster" when m.Realm == DataRealm.Raw => draft.RawFolders.Any(x => Same(x.ClusterId, m.ClusterId) && x.ParentRawFolderId is null && Name(x.Name)) || draft.DriverInstances.Any(x => Same(x.ClusterId, m.ClusterId) && x.RawFolderId is null && Name(x.Name)),
"Cluster" => draft.UnsAreas.Any(x => Same(x.ClusterId, m.ClusterId) && Name(x.Name)),
"RawFolder" => draft.RawFolders.Any(x => Same(x.ParentRawFolderId, m.LocalParentId) && Name(x.Name)) || draft.DriverInstances.Any(x => Same(x.RawFolderId, m.LocalParentId) && Name(x.Name)),
"RawDriver" => draft.Devices.Any(x => Same(x.DriverInstanceId, m.LocalParentId) && Name(x.Name)),
"RawDevice" => draft.TagGroups.Any(x => Same(x.DeviceId, m.LocalParentId) && x.ParentTagGroupId is null && Name(x.Name)) || draft.Tags.Any(x => Same(x.DeviceId, m.LocalParentId) && x.TagGroupId is null && Name(x.Name)),
"RawTagGroup" => draft.TagGroups.Any(x => Same(x.ParentTagGroupId, m.LocalParentId) && Name(x.Name)) || draft.Tags.Any(x => Same(x.TagGroupId, m.LocalParentId) && Name(x.Name)),
"UnsArea" => draft.UnsLines.Any(x => Same(x.UnsAreaId, m.LocalParentId) && Name(x.Name)),
"UnsLine" => draft.Equipment.Any(x => Same(x.UnsLineId, m.LocalParentId) && Name(x.Name)),
"Equipment" => draft.VirtualTags.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.Name)) || draft.ScriptedAlarms.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.Name)) || draft.UnsTagReferences.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.DisplayNameOverride ?? draft.Tags.FirstOrDefault(t => Same(t.TagId, x.TagId))?.Name)),
_ => false
};
}
bool RootIsAncestor(RemoteNamespaceMapping mapping)
{
var kind = mapping.LocalParentKind;
var current = mapping.LocalParentId;
var seen = new HashSet<string>(Ids);
while (!string.IsNullOrEmpty(current) && seen.Add(kind + ":" + current))
{
if (Same(current, mapping.RemoteRootEntityId)) return true;
switch (kind)
{
case "RawFolder":
var folder = draft.RawFolders.FirstOrDefault(x => Same(x.RawFolderId, current));
if (folder is null) return false;
current = folder.ParentRawFolderId ?? folder.ClusterId;
kind = folder.ParentRawFolderId is null ? "Cluster" : "RawFolder";
break;
case "RawDriver":
var driver = draft.DriverInstances.FirstOrDefault(x => Same(x.DriverInstanceId, current));
if (driver is null) return false;
current = driver.RawFolderId ?? driver.ClusterId;
kind = driver.RawFolderId is null ? "Cluster" : "RawFolder";
break;
case "RawDevice":
current = draft.Devices.FirstOrDefault(x => Same(x.DeviceId, current))?.DriverInstanceId ?? "";
kind = "RawDriver";
break;
case "RawTagGroup":
var group = draft.TagGroups.FirstOrDefault(x => Same(x.TagGroupId, current));
if (group is null) return false;
current = group.ParentTagGroupId ?? group.DeviceId;
kind = group.ParentTagGroupId is null ? "RawDevice" : "RawTagGroup";
break;
case "Equipment":
current = draft.Equipment.FirstOrDefault(x => Same(x.EquipmentId, current))?.UnsLineId ?? "";
kind = "UnsLine";
break;
case "UnsLine":
current = draft.UnsLines.FirstOrDefault(x => Same(x.UnsLineId, current))?.UnsAreaId ?? "";
kind = "UnsArea";
break;
case "UnsArea":
current = draft.UnsAreas.FirstOrDefault(x => Same(x.UnsAreaId, current))?.ClusterId ?? "";
kind = "Cluster";
break;
default:
return false;
}
}
return false;
}
foreach (var mapping in draft.RemoteNamespaceMappings.Where(x => x.Enabled))
{
var id = mapping.RemoteNamespaceMappingId;
var connection = draft.DataConnections.FirstOrDefault(x => Same(x.DataConnectionId, mapping.DataConnectionId));
if (string.IsNullOrWhiteSpace(id) || mapping.Revision <= 0 || connection is null || !connection.Enabled || !Same(connection.ClusterId, mapping.ClusterId))
Add("DataMappingConnectionInvalid", id, "An enabled mapping requires an enabled connection owned by the same cluster.");
if (!NodesValid(mapping.ConsumerNodeIds, mapping.ClusterId) || connection is null ||
mapping.ConsumerNodeIds.Any(n => !connection.ConsumerNodeIds.Contains(n, Ids)))
Add("DataMappingConsumerScopeInvalid", id, "Mapping consumers must be a nonempty subset of connection consumers.");
if (!Enum.IsDefined(mapping.Realm) || mapping.Realm == DataRealm.Unspecified || mapping.Realm != mapping.RemoteRealm)
Add("DataMappingRealmMismatch", id, "Local and remote realms must be the same supported realm.");
if (!KindInRealm(mapping.LocalParentKind, mapping.Realm) || mapping.LocalParentKind is "RawTag" or "UnsTagReference" or "VirtualTag" ||
!Same(Owner(mapping.LocalParentKind, mapping.LocalParentId), mapping.ClusterId))
Add("DataMappingParentInvalid", id, "Mapping parent must be a local entity in the selected realm and cluster.");
if (!ValidSegment(mapping.BranchName, mapping.Realm))
Add("DataMappingNameInvalid", id, "Mapping branch name must be a valid realm segment.");
var expectedNamespaceUri = mapping.RemoteRealm switch
{
DataRealm.Raw => V3NodeIds.RawNamespaceUri,
DataRealm.Uns => V3NodeIds.UnsNamespaceUri,
_ => null
};
if (string.IsNullOrWhiteSpace(mapping.RemoteRootEntityId) || expectedNamespaceUri is null ||
!string.Equals(mapping.RemoteNamespaceUri, expectedNamespaceUri, StringComparison.Ordinal) ||
string.IsNullOrWhiteSpace(mapping.RemoteIdentifierKind) || string.IsNullOrWhiteSpace(mapping.RemoteIdentifier))
Add("DataMappingRootInvalid", id, "A stable remote entity and canonical address are required.");
if (mapping.ExpectedValueKind is { } valueKind && (!Enum.IsDefined(valueKind) || valueKind == DataValueKind.Unspecified ||
(valueKind == DataValueKind.Array && (mapping.ExpectedArrayElementKind is not { } elementKind || !DataValue.IsSupportedArrayElementKind(elementKind))) ||
(valueKind != DataValueKind.Array && mapping.ExpectedArrayElementKind is not null)) ||
(mapping.ExpectedValueKind is null && mapping.ExpectedArrayElementKind is not null))
Add("DataMappingTypeInvalid", id, "Expected leaf value and array element types must be supported and consistent.");
if (connection is not null && draft.RemoteNamespaceMappings.Any(other => Same(other.ClusterId, connection.ExpectedClusterId) && Same(other.RemoteNamespaceMappingId, mapping.RemoteRootEntityId)))
Add("DataMappingProjectionLoop", id, "Projected mappings cannot be re-exported or mounted as roots.");
if (connection is not null && Same(connection.ExpectedClusterId, mapping.ClusterId) && RootIsAncestor(mapping))
Add("DataMappingProjectionLoop", id, "A root cannot be mounted under itself.");
if (LocalCollision(mapping) || draft.RemoteNamespaceMappings.Any(other => !ReferenceEquals(other, mapping) && other.Enabled &&
Same(other.ClusterId, mapping.ClusterId) && other.Realm == mapping.Realm && Same(other.LocalParentKind, mapping.LocalParentKind) &&
Same(other.LocalParentId, mapping.LocalParentId) && string.Equals(other.BranchName, mapping.BranchName, StringComparison.Ordinal)))
Add("DataMappingNameCollision", id, "A mapping branch collides with an existing sibling.");
if (!ValidOps(mapping.AllowedOperations) || connection is null || (Understood(mapping.AllowedOperations) & ~connection.AllowedOperations) != 0 ||
(mapping.AllowedOperations.HasFlag(DataOperations.Write) && !mapping.WriteThrough))
Add("DataMappingOperationsInvalid", id, "Mapping operations must be permitted by the connection and write-through policy.");
if (mapping.MaxProjectionNodes <= 0 || mapping.MaxProjectionDepth <= 0 || mapping.MetadataLeaseMilliseconds <= 0 ||
mapping.StaleTimeoutMilliseconds <= 0 || mapping.SamplingIntervalMilliseconds <= 0 || mapping.PublishingIntervalMilliseconds <= 0 ||
mapping.MaxHistoryAssemblyBytesPerRequest <= 0 || mapping.MaxHistoryAssemblyBytesPerRequest > MaxHistoryAssemblyBytesLimit ||
mapping.MaxConditions <= 0 || mapping.MaxConditions > MaxConditionsLimit ||
!ConditionTimeout(mapping.ConditionStaleTimeoutMilliseconds) || !ConditionTimeout(mapping.ConditionMethodTimeoutMilliseconds) ||
!ConditionTimeout(mapping.ConditionSnapshotTimeoutMilliseconds))
Add("DataMappingLimitInvalid", id, "Mapping limits and intervals must be positive and the metadata lease bounded.");
}
foreach (var export in draft.DataExports.Where(x => x.Enabled))
{
var id = export.DataExportId;
if (string.IsNullOrWhiteSpace(id) || export.Revision <= 0 || string.IsNullOrWhiteSpace(export.PrincipalId) ||
!Enum.IsDefined(export.Realm) || export.Realm == DataRealm.Unspecified || !KindInRealm(export.RootKind, export.Realm) ||
!Same(Owner(export.RootKind, export.RootEntityId), export.ClusterId))
Add("DataExportRootInvalid", id, "Export requires a named principal and an origin-local root in its realm.");
if (!ValidOps(export.AllowedOperations)) Add("DataExportOperationsInvalid", id, "Export operations must be a supported nonempty subset.");
if (export.MaxBatchItems <= 0 || export.MaxPageItems <= 0 || export.MaxMonitoredItems <= 0 || export.MaxStreams <= 0 ||
export.MaxConcurrentHistoryReads <= 0 || export.MaxConcurrentHistoryReads > MaxConcurrentHistoryReadsLimit ||
export.MaxHistoryValuesPerPage <= 0 || export.MaxHistoryValuesPerPage > MaxHistoryValuesPerPageLimit ||
export.MaxHistoryResponseBytes < MinHistoryResponseBytesLimit || export.MaxHistoryResponseBytes > MaxHistoryResponseBytesLimit ||
export.MaxConditions <= 0 || export.MaxConditions > MaxConditionsLimit)
Add("DataExportLimitInvalid", id, "Export limits must be positive.");
// A2 (plan §5.6 Q2): the Galaxy service-identity ack opt-in means nothing without the acknowledge grant. The RAW
// bits are checked in both modes: at authoring AlarmAcknowledge is still outside the known set (A2b), so the flag
// must stay false; a deployed row from a newer central that carries both is tolerated (the flag is inert here).
if (export.AllowGalaxyServiceAck && !export.AllowedOperations.HasFlag(DataOperations.AlarmAcknowledge))
Add("DataExportGalaxyAckInvalid", id, "Galaxy service acknowledgement can be allowed only on an export that grants AlarmAcknowledge.");
}
return errors;
}
/// <summary>
/// Non-blocking capacity warnings (plan §5.5/§6): one per consumer node whose enabled <see cref="DataOperations.AlarmSubscribe"/>
/// mappings could together import more condition nodes (Σ <c>MaxConditions</c> × <see cref="NodesPerImportedCondition"/>)
/// than the host cap <c>DataConnections:MaxImportedConditionNodes</c>. The runtime still admits mappings in deployed order
/// and refuses the ones that would cross the cap (<c>Unavailable(ConditionCapacity)</c>); this only says so up front. The
/// validator's error list has no warning channel, so these are returned separately and never block authoring or deploy.
/// </summary>
public static IReadOnlyList<ValidationError> ConditionCapacityWarnings(DraftSnapshot draft,
int maxImportedConditionNodes = DefaultMaxImportedConditionNodes)
{
ArgumentNullException.ThrowIfNull(draft);
return draft.RemoteNamespaceMappings
.Where(m => m.Enabled && m.AllowedOperations.HasFlag(DataOperations.AlarmSubscribe))
.SelectMany(m => m.ConsumerNodeIds.Distinct(Ids).Select(node => (Node: node, Nodes: (long)Math.Max(0, m.MaxConditions) * NodesPerImportedCondition)))
.GroupBy(x => x.Node, Ids)
.Select(g => (Node: g.Key, Total: g.Sum(x => x.Nodes)))
.Where(x => x.Total > maxImportedConditionNodes)
.OrderBy(x => x.Node, StringComparer.OrdinalIgnoreCase)
.Select(x => new ValidationError("DataConditionCapacityWarning",
$"Consumer node {x.Node}: its alarm mappings' MaxConditions × {NodesPerImportedCondition} = {x.Total} condition nodes exceeds " +
$"DataConnections:MaxImportedConditionNodes ({maxImportedConditionNodes}); mappings past the cap will be Unavailable (ConditionCapacity).",
x.Node))
.ToArray();
}
}