feat(grpc-data): X0 node-side tolerant readers drop unknown operation bits per row (counted) instead of rejecting the snapshot

Covers the deployment runtime (plan site) plus two node-side validator passes the plan missed:
DeploymentArtifact data-row parse and LocalExportCatalog.Compile now use DataConnectionValidator.ValidateDeployed.
Authoring (Validate) still rejects the reserved bits.
This commit is contained in:
Joseph Doherty
2026-11-23 17:21:35 -05:00
parent d96eafd138
commit a5ef7ea6d8
8 changed files with 341 additions and 13 deletions
@@ -9,17 +9,33 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation;
/// <summary>Validates deployed data-service configuration without resolving consumer-side secrets.</summary>
public static class DataConnectionValidator
{
private const DataOperations KnownOperations = DataOperations.Browse | DataOperations.Metadata |
DataOperations.Read | DataOperations.Write | DataOperations.Subscribe;
/// <summary>
/// The operations AUTHORING may grant. Deliberately the v1 set: it grows only in the phase that implements a bit
/// (H2, A2), so authoring cannot get ahead of the code (plan section 4.3, "grow site").
/// </summary>
private const DataOperations KnownOperations = DataOperationSets.V1;
private static readonly StringComparer Ids = StringComparer.OrdinalIgnoreCase;
public static IReadOnlyList<ValidationError> Validate(DraftSnapshot draft)
/// <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 this build does not understand 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. Each consumer of the rows keeps only the bits it understands (fail closed).
/// </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 && (operations & ~KnownOperations) == 0;
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();
@@ -251,7 +267,7 @@ public static class DataConnectionValidator
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 || (mapping.AllowedOperations & ~connection.AllowedOperations) != 0 ||
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 ||
@@ -212,7 +212,7 @@ public static class DataConnectionRegistration
var eligible = state.Generation > 0 && Enum.TryParse<RedundancyRole>(state.Role, out var actual)
&& DataConnectionRoleAdapter.MayAcquire(mode, state.WarmRole, actual);
return new DataConnectionConsumerRoleSnapshot(mode, eligible, state.Generation);
});
}, logger: sp.GetService<Microsoft.Extensions.Logging.ILoggerFactory>()?.CreateLogger<DataConnectionDeploymentRuntime>());
return runtime;
});
services.AddSingleton(sp =>
@@ -1,3 +1,7 @@
using System.Diagnostics.Metrics;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
@@ -39,7 +43,15 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
internal bool Ready;
internal int Leases;
}
/// <summary>Counter of connection rows whose unknown operation bits were dropped (X0 tolerant reader).</summary>
public const string UnknownOperationsCounterName = "otopcua.dataconnection.unknown_operations_dropped";
private static readonly Counter<long> UnknownOperationsCounter = OtOpcUaTelemetry.Meter.CreateCounter<long>(
UnknownOperationsCounterName, unit: "{row}",
description: "Data-connection rows carrying operation bits this node does not understand; the bits were dropped (no grant).");
private readonly object _sync = new();
private readonly ILogger _log;
private IReadOnlyDictionary<string, DataOperations> _droppedOperations = new Dictionary<string, DataOperations>();
private long _unknownOperationRows;
private readonly string _node, _owner;
private readonly IDataConnectionSecurityProvider _security;
private readonly IDataConnectionScopeActivator _activator;
@@ -64,8 +76,9 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
public DataConnectionDeploymentRuntime(string nodeId, string ownerCluster, IDataConnectionSecurityProvider security,
IDataConnectionScopeActivator scopeActivator, int maxConnections, TimeProvider? clock = null,
Func<bool>? consumerMayAcquire = null, bool useCompactBatches = true,
Func<RedundancyMode, DataConnectionConsumerRoleSnapshot?>? consumerRoleSnapshot = null)
Func<RedundancyMode, DataConnectionConsumerRoleSnapshot?>? consumerRoleSnapshot = null, ILogger? logger = null)
{
_log = logger ?? NullLogger.Instance;
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId); ArgumentException.ThrowIfNullOrWhiteSpace(ownerCluster);
if (maxConnections <= 0) throw new ArgumentOutOfRangeException(nameof(maxConnections));
_node = nodeId; _owner = ownerCluster; _security = security ?? throw new ArgumentNullException(nameof(security));
@@ -81,6 +94,13 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
/// <summary>True only after the current scope version and allowlist are durably accepted.</summary>
public bool CurrentScopeReady { get { lock (_sync) return !_disposed && _scopeReady; } }
/// <summary>
/// X0 diagnostics: per enabled connection of the current artifact, the operation bits it was authored with that
/// this node does not understand and therefore dropped (an unknown grant is no grant). Empty when none.
/// </summary>
public IReadOnlyDictionary<string, DataOperations> DroppedUnknownOperations { get { lock (_sync) return _droppedOperations; } }
/// <summary>Cumulative count of connection rows that had unknown bits dropped, once per accepted artifact.</summary>
public long UnknownOperationRowsDropped => Interlocked.Read(ref _unknownOperationRows);
/// <summary>Configured redundancy mode from the current validated artifact.</summary>
public RedundancyMode CurrentConsumerMode { get { lock (_sync) return _desired?.ConsumerMode ?? RedundancyMode.None; } }
@@ -133,6 +153,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
if (snapshot.Connections.Count > _maximum) throw new ArgumentException("Connection capacity exceeded.", nameof(snapshot));
var specs = new Dictionary<string, Spec>(StringComparer.OrdinalIgnoreCase);
var allow = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var dropped = new Dictionary<string, DataOperations>(StringComparer.OrdinalIgnoreCase);
foreach (var item in snapshot.Connections)
{
ArgumentNullException.ThrowIfNull(item);
@@ -148,15 +169,18 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
item.MaxMessageBytes <= 0 || item.MaxStreams <= 0 || item.MaxMonitoredItems <= 0 || item.MaxPendingBytes <= 0 ||
item.Endpoints is null || item.Endpoints.Count == 0 || item.Endpoints.Count > 32 || item.EligibleTargetNodeIds is null)
throw new ArgumentException("Connection limits or endpoints are invalid.", nameof(snapshot));
const DataOperations known = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe;
if ((item.AllowedOperations & ~known) != 0) throw new ArgumentException("Unknown operation.", nameof(snapshot));
// X0 tolerant reader (plan §4.3): a bit a newer central authored that this build does not implement is
// dropped from THIS row only, fail closed, and counted. It used to reject the whole snapshot. A row left
// with no understood operation stays configured and grants nothing.
var operations = item.AllowedOperations & DataOperationSets.Understood;
if (operations != item.AllowedOperations) dropped[item.DataConnectionId] = item.AllowedOperations & ~DataOperationSets.Understood;
var endpoints = item.Endpoints.Select(value => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps
? uri : throw new ArgumentException("Only HTTPS endpoints are accepted.", nameof(snapshot))).Distinct().ToArray();
var eligible = new HashSet<string>(item.EligibleTargetNodeIds, StringComparer.OrdinalIgnoreCase);
if (target.Mode == DataTargetMode.Cluster && (eligible.Count == 0 || eligible.Any(string.IsNullOrWhiteSpace)))
throw new ArgumentException("Cluster target has no eligible nodes.", nameof(snapshot));
var spec = new Spec(item.DataConnectionId, item.Revision, target, endpoints, eligible, item.SecretReference,
item.AllowedOperations, TimeSpan.FromMilliseconds(item.TimeoutMilliseconds), item.MaxBatchItems,
operations, TimeSpan.FromMilliseconds(item.TimeoutMilliseconds), item.MaxBatchItems,
item.MaxPageItems, item.MaxMessageBytes, item.MaxStreams, item.MaxMonitoredItems, item.MaxPendingBytes);
if (!specs.TryAdd(spec.Id, spec) || !allow.TryAdd(spec.Id, spec.Secret))
throw new ArgumentException("Duplicate connection identity.", nameof(snapshot));
@@ -176,6 +200,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
{
if (snapshot.ScopeVersion != previous.ScopeVersion || snapshot.ConsumerMode != previous.ConsumerMode || !SameSpecs(previous.Specs, specs))
throw new InvalidOperationException("An artifact revision cannot identify different definitions.");
// Same revision re-applied: identical rows, so the dropped set is unchanged and is not recounted.
if (!_attemptPending) { if (!_scopeReady) DisarmRetryLocked(); WakeLocked(); return; }
}
}
@@ -183,7 +208,9 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
var generation = checked(++_generation);
_routeRevisions.Clear();
foreach (var id in specs.Keys) _routeRevisions.Add(id, generation);
var priorRevision = _desired?.ArtifactRevision;
_desired = new(snapshot.ScopeVersion, snapshot.ArtifactRevision, generation, snapshot.ConsumerMode, specs, allow);
RecordDroppedLocked(snapshot.ArtifactRevision, priorRevision, dropped);
_scopeReady = false;
old = _entries.Values.ToArray(); _entries.Clear();
ApplyManagerScopeLocked(_desired);
@@ -191,6 +218,19 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
WakeLocked();
}
}
private void RecordDroppedLocked(string revision, string? priorRevision, Dictionary<string, DataOperations> dropped)
{
_droppedOperations = dropped;
if (dropped.Count == 0 || string.Equals(revision, priorRevision, StringComparison.Ordinal)) return;
Interlocked.Add(ref _unknownOperationRows, dropped.Count);
foreach (var (id, bits) in dropped)
{
UnknownOperationsCounter.Add(1);
_log.LogWarning("Data connection {DataConnectionId} in artifact {ArtifactRevision} grants operation bits {UnknownOperations} " +
"this node does not implement; they were dropped (no grant). Upgrade this node before relying on them.",
id, revision, (int)bits);
}
}
private static bool SameAllowlist(IReadOnlyDictionary<string, string> left, IReadOnlyDictionary<string, string> right) =>
left.Count == right.Count && left.All(x => right.TryGetValue(x.Key, out var value) && string.Equals(value, x.Value, StringComparison.Ordinal));
private static bool SameSpecs(IReadOnlyDictionary<string, Spec> left, IReadOnlyDictionary<string, Spec> right) =>
@@ -488,6 +528,8 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDisposable
RouteIdentity = routeIdentity;
}
internal Func<bool> RouteCurrent => _routeCurrent;
/// <summary>The configured row's operations, already masked to the understood set.</summary>
internal DataOperations AllowedOperations => _allowed;
public IDataConnection Connection => this;
public CancellationToken CancellationToken => _scope;
public DataTarget Target => _inner.Target;
@@ -25,7 +25,7 @@ public sealed partial class LocalExportCatalog
{
ArgumentNullException.ThrowIfNull(snapshot);
serving.Validate(requireEpochs: true);
if (DataConnectionValidator.Validate(snapshot).Count != 0)
if (DataConnectionValidator.ValidateDeployed(snapshot).Count != 0)
throw new InvalidDataException("Origin catalog configuration is invalid.");
var cluster = snapshot.ClusterId;
var ids = StringComparer.OrdinalIgnoreCase;
@@ -89,7 +89,8 @@ public sealed partial class LocalExportCatalog
|| export.MaxMonitoredItems <= 0 || export.MaxStreams <= 0)
throw new ArgumentException("Export has no valid origin root or policy.", nameof(exports));
rules.Add(new(export.DataExportId, export.PrincipalId, export.Realm, wholeRealm ? null : roots[0].Metadata.View, wholeRealm,
export.AllowedOperations, export.MaxBatchItems, export.MaxPageItems, export.MaxMonitoredItems, export.MaxStreams));
// X0: an export bit this build does not implement grants nothing (a None-after-mask rule is kept and inert).
export.AllowedOperations & DataOperationSets.Understood, export.MaxBatchItems, export.MaxPageItems, export.MaxMonitoredItems, export.MaxStreams));
}
_exports = rules.ToArray();
Nodes = new ReadOnlyCollection<LocalDataNode>(_nodes.Values.ToArray());
@@ -332,7 +332,7 @@ internal sealed partial class ParsedDeploymentArtifact
{
var requested = ids.ToHashSet(DataIds);
var error = DataConnectionValidator
.Validate(snapshot)
.ValidateDeployed(snapshot)
.FirstOrDefault(x => x.Context is not null && requested.Contains(x.Context));
if (error is not null)
throw InvalidRow(error.Context);
@@ -0,0 +1,66 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests.DataConnections;
/// <summary>
/// X0 grow site: authoring keeps rejecting the reserved bits until the phase that implements each one, so central
/// cannot hand a node a grant it does not implement. Only the node-side re-validation of a deployed artifact tolerates them.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")]
public sealed class GrpcDataReservedOperationAuthoringTests
{
public static TheoryData<int> ReservedBits => new(32, 64, 128, 256, 512, 1 << 20);
[Theory]
[MemberData(nameof(ReservedBits))]
public void Authoring_rejects_a_reserved_bit_on_connections_exports_and_mappings(int bit)
{
var errors = DataConnectionValidator.Validate(Snapshot(DataOperations.Read | (DataOperations)bit));
errors.ShouldContain(x => x.Code == "DataConnectionOperationsInvalid" && x.Context == "connection");
errors.ShouldContain(x => x.Code == "DataExportOperationsInvalid" && x.Context == "export");
errors.ShouldContain(x => x.Code == "DataMappingOperationsInvalid" && x.Context == "mapping");
}
[Fact]
public void Authoring_accepts_the_v1_set_unchanged()
{
var errors = DataConnectionValidator.Validate(Snapshot(DataOperations.Read));
errors.ShouldNotContain(x => x.Code.EndsWith("OperationsInvalid", StringComparison.Ordinal));
DataOperationSets.V1.ShouldBe(DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe);
}
[Theory]
[MemberData(nameof(ReservedBits))]
public void Deployed_revalidation_ignores_reserved_bits_but_keeps_every_other_operation_rule(int bit)
{
DataConnectionValidator.ValidateDeployed(Snapshot(DataOperations.Read | (DataOperations)bit))
.ShouldNotContain(x => x.Code.EndsWith("OperationsInvalid", StringComparison.Ordinal));
// Still rejected node-side: an empty grant, and a mapping wider than its connection in UNDERSTOOD bits.
DataConnectionValidator.ValidateDeployed(Snapshot(DataOperations.None))
.ShouldContain(x => x.Code == "DataConnectionOperationsInvalid");
var wider = Snapshot(DataOperations.Read | (DataOperations)bit);
wider.RemoteNamespaceMappings[0].AllowedOperations = DataOperations.Read | DataOperations.Subscribe;
DataConnectionValidator.ValidateDeployed(wider).ShouldContain(x => x.Code == "DataMappingOperationsInvalid");
}
private static DraftSnapshot Snapshot(DataOperations operations) => new()
{
GenerationId = 1, ClusterId = "local",
DataConnections = [new DataConnection
{
DataConnectionId = "connection", ClusterId = "local", Revision = 1, Enabled = true, AllowedOperations = operations,
ConsumerNodeIds = [], EligibleTargetNodeIds = [], Endpoints = ["https://origin.example:7443"],
MaxMessageBytes = 1, MaxBatchItems = 1, MaxPageItems = 1, MaxStreams = 1, MaxMonitoredItems = 1, MaxPendingBytes = 1, TimeoutMilliseconds = 1,
}],
DataExports = [new DataExport { DataExportId = "export", ClusterId = "local", Enabled = true, AllowedOperations = operations, PrincipalId = "p", Revision = 1 }],
RemoteNamespaceMappings = [new RemoteNamespaceMapping
{
RemoteNamespaceMappingId = "mapping", ClusterId = "local", DataConnectionId = "connection", Enabled = true,
AllowedOperations = operations, ConsumerNodeIds = [], Revision = 1,
}],
};
}
@@ -0,0 +1,203 @@
using System.Text;
using System.Text.Json.Nodes;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// X0 mixed-version tolerance (plan §4.3, test "R"). A newer central may author an operation bit this node does
/// not implement. Before X0 that rejected the WHOLE data-connection snapshot (every connection on the node went
/// down); after X0 the unknown bit is dropped from that row only (an unknown grant is no grant) and counted.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")]
public sealed class GrpcDataUnknownOperationToleranceTests
{
private static DataConnection Definition(string id, DataOperations operations) => new()
{
DataConnectionId = id, ClusterId = "owner", Revision = 1, Enabled = true,
ConsumerNodeIds = ["node-a"], TargetMode = DataTargetMode.Node,
ExpectedClusterId = "target", ExpectedNodeId = "remote", Endpoints = ["https://remote.example:8443"],
SecretReference = "secret:data/" + id, SecretScopeClusterId = "owner", AllowedOperations = operations,
MaxMessageBytes = 65536, MaxBatchItems = 16, MaxPageItems = 16, MaxStreams = 2,
MaxMonitoredItems = 16, MaxPendingBytes = 65536, TimeoutMilliseconds = 5000
};
[Fact]
public async Task Unknown_bit_on_one_row_is_dropped_from_that_row_only_and_counted()
{
var activator = new Activator();
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
var history = Definition("history", DataOperations.Read | DataOperations.Browse | DataOperations.HistoryRead | DataOperations.AlarmShelve);
var plain = Definition("plain", DataOperations.Read | DataOperations.Subscribe);
var future = Definition("future", (DataOperations)(1 << 20) | DataOperations.AlarmSubscribe);
// The pre-X0 runtime threw ArgumentException("Unknown operation.") here for the whole snapshot.
Should.NotThrow(() => runtime.Apply(new(1, "artifact-1", [history, plain, future])));
await EventuallyAsync(() => runtime.CurrentScopeReady);
(await Lease(runtime, "history")).ShouldBe(DataOperations.Read | DataOperations.Browse);
(await Lease(runtime, "plain")).ShouldBe(DataOperations.Read | DataOperations.Subscribe);
// A row left with no understood operation stays configured and grants nothing (fail closed).
(await Lease(runtime, "future")).ShouldBe(DataOperations.None);
runtime.DroppedUnknownOperations.ShouldBe(new Dictionary<string, DataOperations>(StringComparer.OrdinalIgnoreCase)
{
["history"] = DataOperations.HistoryRead | DataOperations.AlarmShelve,
["future"] = (DataOperations)(1 << 20) | DataOperations.AlarmSubscribe,
});
runtime.UnknownOperationRowsDropped.ShouldBe(2);
// The input rows are not mutated: the drop is the node's reading, not a rewrite of the artifact.
history.AllowedOperations.ShouldBe(DataOperations.Read | DataOperations.Browse | DataOperations.HistoryRead | DataOperations.AlarmShelve);
activator.Allowlists.Last().Keys.Order(StringComparer.OrdinalIgnoreCase).ShouldBe(["future", "history", "plain"]);
}
[Fact]
public async Task Reapplying_the_same_revision_does_not_recount_and_a_clean_artifact_clears_the_diagnostic()
{
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), new Activator(), 4);
var snapshot = new DataConnectionDeploymentSnapshot(1, "artifact-1", [Definition("history", DataOperations.Read | DataOperations.HistoryRead)]);
runtime.Apply(snapshot);
runtime.Apply(snapshot);
runtime.UnknownOperationRowsDropped.ShouldBe(1);
runtime.DroppedUnknownOperations.ShouldContainKey("history");
runtime.Apply(new(2, "artifact-2", [Definition("history", DataOperations.Read)]));
runtime.DroppedUnknownOperations.ShouldBeEmpty();
runtime.UnknownOperationRowsDropped.ShouldBe(1);
}
[Fact]
public void Node_side_artifact_parse_accepts_rows_carrying_bits_a_newer_central_authored()
{
var root = Fixture();
root["DataConnections"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead);
root["DataExports"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead | DataOperations.AlarmSubscribe);
root["RemoteNamespaceMappings"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.HistoryRead);
using var parsed = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(root.ToJsonString()));
// Pre-X0 each of these threw InvalidDataException through the node-side DataConnectionValidator pass.
// Rows come back as authored; each consumer keeps only the bits it understands.
parsed.ParseDataConnections("node-a").ShouldHaveSingleItem().AllowedOperations.ShouldBe(
DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead);
parsed.ParseDataExports("node-b").ShouldHaveSingleItem().DataExportId.ShouldBe("export-a");
parsed.ParseRemoteNamespaceMappings("node-a").ShouldHaveSingleItem().RemoteNamespaceMappingId.ShouldBe("mapping-a");
}
[Fact]
public void Node_side_artifact_parse_still_rejects_what_it_rejected_before()
{
// Tolerance is only for unknown bits: a row with no operations at all, or a mapping granting an understood
// operation its connection lacks, is still invalid.
var none = Fixture();
none["DataConnections"]![0]!["AllowedOperations"] = 0;
using (var parsed = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(none.ToJsonString())))
Should.Throw<InvalidDataException>(() => parsed.ParseDataConnections("node-a"));
var wider = Fixture();
wider["RemoteNamespaceMappings"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Subscribe);
using (var parsed = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(wider.ToJsonString())))
Should.Throw<InvalidDataException>(() => parsed.ParseRemoteNamespaceMappings("node-a"));
}
[Fact]
public void Origin_catalog_compiles_an_export_with_unknown_bits_and_grants_only_what_it_understands()
{
using var fixture = new LocalDataFixture();
var snapshot = new DraftSnapshot
{
GenerationId = 1, ClusterId = "cluster",
ServerClusters = [new() { ClusterId = "cluster", Name = "Cluster", Enterprise = "Enterprise", Site = "Site", CreatedBy = "test", RedundancyMode = RedundancyMode.None }],
RawFolders = [new() { RawFolderId = "folder", ClusterId = "cluster", Name = "Plant" }],
DataExports =
[
new() { DataExportId = "history", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "Cluster",
RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead },
new() { DataExportId = "alarms-only", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = "Cluster",
RootEntityId = "cluster", PrincipalId = "other", AllowedOperations = DataOperations.AlarmSubscribe | DataOperations.AlarmAcknowledge },
],
};
DataConnectionValidator.Validate(snapshot).ShouldContain(x => x.Code == "DataExportOperationsInvalid", "authoring still rejects reserved bits");
// Pre-X0 Compile threw InvalidDataException("Origin catalog configuration is invalid."): the whole origin went dark.
var catalog = LocalExportCatalog.Compile(snapshot, fixture.Serving, fixture.Activation.CaptureAuthority());
catalog.ExportOperations("peer").ShouldBe(DataOperations.Browse | DataOperations.Read);
catalog.ExportOperations("other").ShouldBe(DataOperations.None);
}
private static async Task<DataOperations> Lease(DataConnectionDeploymentRuntime runtime, string id)
{
DataConnectionDeploymentLease? lease = null;
await EventuallyAsync(() => runtime.TryAcquire(id, out lease));
using (lease) return lease!.AllowedOperations;
}
private static async Task EventuallyAsync(Func<bool> condition)
{
for (var i = 0; i < 250; i++)
{
if (condition()) return;
await Task.Delay(20, TestContext.Current.CancellationToken);
}
throw new TimeoutException("Expected deployment state did not arrive.");
}
private sealed class Activator : IDataConnectionScopeActivator
{
public List<IReadOnlyDictionary<string, string>> Allowlists { get; } = [];
public Task SetScopeAsync(long version, IReadOnlyDictionary<string, string> allowlist, CancellationToken cancellationToken)
{
lock (Allowlists) Allowlists.Add(new Dictionary<string, string>(allowlist, StringComparer.OrdinalIgnoreCase));
return Task.CompletedTask;
}
}
private sealed class Security : IDataConnectionSecurityProvider
{
public event Action<string>? Changed { add { } remove { } }
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
ValueTask.FromResult<DataConnectionSecurity?>(new("1", "trust", "key", () => new NoNetwork()));
}
private sealed class NoNetwork : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
throw new InvalidOperationException("This tolerance test must not use the network.");
}
private static JsonObject Fixture() => JsonNode.Parse(
"""
{
"Clusters": [{"ClusterId":"local","Name":"Local","Enterprise":"ent","Site":"site","RedundancyMode":0,"CreatedBy":"test","Enabled":true}],
"Nodes": [
{"NodeId":"node-a","ClusterId":"local","Host":"node-a","ApplicationUri":"urn:node-a","CreatedBy":"test","Enabled":true,"MaintenanceMode":false},
{"NodeId":"node-b","ClusterId":"local","Host":"node-b","ApplicationUri":"urn:node-b","CreatedBy":"test","Enabled":true,"MaintenanceMode":false}
],
"RawFolders": [{"RawFolderId":"local-root","ClusterId":"local","Name":"Local"}],
"DataConnections": [{
"DataConnectionId":"connection-a","ClusterId":"local","Revision":3,"Enabled":true,
"ConsumerNodeIds":["node-a"],"TargetMode":1,"Consistency":1,
"ExpectedClusterId":"local","ExpectedNodeId":"node-b","EligibleTargetNodeIds":[],
"Endpoints":["https://node-b:7443"],"SecretReference":"secret:data/upstream",
"SecretScopeClusterId":"local","AllowedOperations":5
}],
"DataExports": [{
"DataExportId":"export-a","ClusterId":"local","Revision":4,"Enabled":true,
"Realm":1,"RootKind":"RawFolder","RootEntityId":"local-root",
"PrincipalId":"peer","AllowedOperations":5
}],
"RemoteNamespaceMappings": [{
"RemoteNamespaceMappingId":"mapping-a","ClusterId":"local","DataConnectionId":"connection-a",
"Revision":5,"Enabled":true,"ConsumerNodeIds":["node-a"],"Realm":1,"RemoteRealm":1,
"LocalParentKind":"RawFolder","LocalParentId":"local-root","BranchName":"Remote",
"RemoteRootEntityId":"origin-root","RemoteNamespaceUri":"https://zb.com/otopcua/raw","RemoteIdentifierKind":"string",
"RemoteIdentifier":"origin-root","AllowedOperations":1,"WriteThrough":false
}]
}
""")!.AsObject();
}