Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataUnknownOperationToleranceTests.cs
T

246 lines
15 KiB
C#

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
{
// A2b made 128/256 understood: "unknown" here means bits no build defines yet (plus the still-reserved AlarmShelve).
private const DataOperations FutureA = (DataOperations)(1 << 11), FutureB = (DataOperations)(1 << 12);
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 | FutureA | DataOperations.AlarmShelve);
var plain = Definition("plain", DataOperations.Read | DataOperations.Subscribe);
var future = Definition("future", (DataOperations)(1 << 30) | FutureB); // A2b: 64/128/256 are understood
// 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"] = FutureA | DataOperations.AlarmShelve,
["future"] = (DataOperations)(1 << 30) | FutureB,
});
runtime.UnknownOperationRowsDropped.ShouldBe(2);
// The production reader: the node diagnostics snapshot carries each row's dropped bits.
var diagnostics = runtime.CaptureDiagnostics().ToDictionary(x => x.ConnectionId);
diagnostics["history"].DroppedUnknownOperations.ShouldBe(FutureA | DataOperations.AlarmShelve);
diagnostics["plain"].DroppedUnknownOperations.ShouldBe(DataOperations.None);
diagnostics["future"].DroppedUnknownOperations.ShouldBe((DataOperations)(1 << 30) | FutureB);
diagnostics["plain"].MappingsWithDroppedOperations.ShouldBeNull("no mapping evidence was supplied");
// 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 | FutureA | 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 | FutureA)]);
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);
// A -> B -> A is an accepted artifact CHANGE each time, so it recounts (documented semantics).
runtime.Apply(new(3, "artifact-1", [Definition("history", DataOperations.Read | FutureA)]));
runtime.UnknownOperationRowsDropped.ShouldBe(2);
}
[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 | FutureA);
root["DataExports"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Read | FutureA | DataOperations.AlarmSubscribe);
root["RemoteNamespaceMappings"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | FutureA);
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 | FutureA);
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 | FutureA },
new() { DataExportId = "alarms-only", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = "Cluster",
RootEntityId = "cluster", PrincipalId = "other", AllowedOperations = FutureA | FutureB }, // A2b: 64/128/256 are understood
],
};
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);
}
[Fact]
public void An_inert_all_unknown_export_does_not_lower_the_principals_limits_on_its_other_exports()
{
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 = "live", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "Cluster",
RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Read,
MaxBatchItems = 100, MaxPageItems = 100, MaxMonitoredItems = 100, MaxStreams = 10 },
new() { DataExportId = "future-only", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = "Cluster",
RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = FutureA | (DataOperations)(1 << 30),
MaxBatchItems = 1, MaxPageItems = 1, MaxMonitoredItems = 1, MaxStreams = 1 },
],
};
var catalog = LocalExportCatalog.Compile(snapshot, fixture.Serving, fixture.Activation.CaptureAuthority());
var limits = new DataLimits(1000, 1000, 1_000_000, 1000, 100, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
var effective = catalog.LimitsFor("peer", limits);
effective.MaxBatchItems.ShouldBe(100);
effective.MaxPageItems.ShouldBe(100);
effective.MaxMonitoredItems.ShouldBe(100);
effective.MaxStreams.ShouldBe(10);
catalog.ExportOperations("peer").ShouldBe(DataOperations.Browse | DataOperations.Read);
}
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();
}