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:
+203
@@ -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();
|
||||
}
|
||||
Reference in New Issue
Block a user