Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs
T
Joseph Doherty d0756bb78e test(grpc-data): H2 wire suite; both v1 gates extended with history-shaped data
Both recorded-v1-client gates now run against origins that grant HistoryRead, advertise history capabilities and
carry HistoryInfo; header-less bytes stay identical to the goldens (not re-recorded). GrpcDataHistoryWireTests: probe
shapes, FAILED_PRECONDITION without the feature, denied/unhistorized/unknown byte-identical with no backend call,
admission, cancel, wiring fault, chunking + lost chunk, release, direct runtime consumer. Endpoint allowlist gains
HistoryRead (the auth middleware rejected it).
2026-11-23 20:48:56 -05:00

316 lines
19 KiB
C#

using System.Collections.Concurrent;
using Google.Protobuf;
using Grpc.Core;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Host.Grpc;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
/// <summary>
/// H2 wire: the real <see cref="DataConnectionGrpcService"/> over the REAL origin stack (<see cref="RealOrigin"/>:
/// LocalDataServices, LocalExportCatalog, the data-plane ACL), with only the node manager's history port faked
/// (<see cref="FakeHistoryPort"/>; the port itself is covered by OpcUaServer <c>OriginHistoryPortTests</c>).
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H2")]
public sealed class GrpcDataHistoryWireTests
{
private static Metadata History => new() { { "x-otopcua-data-features", "history" } };
private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 16, 1 << 20);
private static readonly DateTimeOffset T0 = new(2026, 11, 23, 0, 0, 0, TimeSpan.Zero);
private static DataHistoryReadItem I(string id, DataView view) => new(id, view);
private static W.HistoryReadRequest Raw(params DataHistoryReadItem[] items) => DataHistoryProtoMapper.EncodeRequest(
new DataHistoryReadRequest(new DataHistoryRawDetails(T0, T0.AddHours(1), 0, false), items, Budget));
[Fact]
public async Task Probe_with_history_on_a_history_capable_origin_advertises_field_16_and_bit_32()
{
await using var origin = new RealOrigin();
var bytes = await origin.DriveAsync("GetCapabilities", History);
var response = W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(bytes));
response.History.ShouldNotBeNull();
response.History.Raw.ShouldBeTrue(); response.History.AtTime.ShouldBeTrue(); response.History.Processed.ShouldBeTrue();
response.History.Aggregates.ShouldBe(["Average", "Count"]);
response.History.MaxValuesPerPage.ShouldBe(10_000); response.History.MaxConcurrentReads.ShouldBe(4);
response.History.TimestampResolutionTicks.ShouldBe(10);
(response.Operations & (uint)DataOperations.HistoryRead).ShouldBe((uint)DataOperations.HistoryRead);
// Without the header the same origin answers the v1 golden (also pinned by the real-origin gate).
(await origin.DriveAsync("GetCapabilities", new Metadata())).ShouldBe(GrpcDataV1RealOriginGoldens.Responses["GetCapabilities"]);
}
[Fact]
public async Task Probe_with_history_on_an_origin_without_a_historian_advertises_neither()
{
await using var origin = new RealOrigin(historian: false);
var response = W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(await origin.DriveAsync("GetCapabilities", History)));
response.History.ShouldBeNull();
(response.Operations & (uint)DataOperations.HistoryRead).ShouldBe(0u);
}
[Fact]
public async Task Negotiated_metadata_carries_history_info_only_for_historized_and_granted_nodes()
{
await using var origin = new RealOrigin();
var response = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(await origin.DriveAsync("GetMetadata", History)));
var byId = response.Items.Where(x => x.Value is not null).ToDictionary(x => x.Value.View.Address.Identifier, x => x.Value);
byId["Plant/Modbus/dev1/Flow"].History.Historizing.ShouldBeTrue();
(byId["Plant/Modbus/dev1/Flow"].AllowedOperations & 32u).ShouldBe(32u);
byId["Area1/Line1/Filler/FlowRate"].History.Historizing.ShouldBeTrue();
byId["Plant/Modbus/dev1/Speed"].History.Historizing.ShouldBeFalse();
(byId["Plant/Modbus/dev1/Speed"].AllowedOperations & 32u).ShouldBe(0u);
// Header-less: the golden (no Metadata.history, no bit 32).
(await origin.DriveAsync("GetMetadata", new Metadata())).ShouldBe(GrpcDataV1RealOriginGoldens.Responses["GetMetadata"]);
// A caller whose ACL lacks HistoryRead sees historizing=false on Flow: the same as an unhistorized node.
await using var denied = new RealOrigin(permissions: NodePermissions.Operator & ~NodePermissions.HistoryRead);
var deniedMeta = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(await denied.DriveAsync("GetMetadata", History)));
var flow = deniedMeta.Items.Single(x => x.Value?.View.Address.Identifier == "Plant/Modbus/dev1/Flow").Value;
flow.History.Historizing.ShouldBeFalse();
(flow.AllowedOperations & 32u).ShouldBe(0u);
}
[Fact]
public async Task HistoryRead_without_the_negotiated_feature_is_failed_precondition()
{
await using var origin = new RealOrigin();
var headerless = await Should.ThrowAsync<RpcException>(() => origin.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), new Metadata()));
headerless.StatusCode.ShouldBe(StatusCode.FailedPrecondition);
headerless.Status.Detail.ShouldBe("feature not negotiated");
var conditions = await Should.ThrowAsync<RpcException>(() =>
origin.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), new Metadata { { "x-otopcua-data-features", "conditions" } }));
conditions.StatusCode.ShouldBe(StatusCode.FailedPrecondition);
await using var noHistorian = new RealOrigin(historian: false);
var unservable = await Should.ThrowAsync<RpcException>(() => noHistorian.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History));
unservable.StatusCode.ShouldBe(StatusCode.FailedPrecondition);
origin.History!.Calls.ShouldBe(0);
}
[Fact]
public async Task Denied_and_unhistorized_and_unknown_are_byte_identical_and_never_reach_the_backend()
{
await using var origin = new RealOrigin();
await using var denied = new RealOrigin(permissions: NodePermissions.Operator & ~NodePermissions.HistoryRead);
var unhistorized = await origin.HistoryAsync(Raw(I("x", RealOriginRequests.Speed)), History);
var aclDenied = await denied.HistoryAsync(Raw(I("x", RealOriginRequests.Flow)), History);
var unknown = await origin.HistoryAsync(Raw(I("x", RealOriginRequests.Missing)), History);
var folder = await origin.HistoryAsync(Raw(I("x", RealOriginRequests.Device)), History);
var foreign = await origin.HistoryAsync(Raw(I("x", RealOriginRequests.Flow with { Subject = "elsewhere" })), History);
var expected = unhistorized.Items.Single().ToByteArray();
foreach (var other in new[] { aclDenied, unknown, folder, foreign })
other.Items.Single().ToByteArray().ShouldBe(expected);
unhistorized.Items.Single().StatusCode.ShouldBe(0x80720000u); // Bad_HistoryOperationUnsupported
unhistorized.Items.Single().HasDiagnostic.ShouldBeFalse();
origin.History!.Calls.ShouldBe(0);
denied.History!.Calls.ShouldBe(0, "the ACL refusal happens before the tagname lookup and the backend");
denied.History.HistorizedLookups.ShouldBe(0, "ingress order: export grant, ACL, then the tagname");
}
[Fact]
public async Task A_granted_historized_read_serves_values_verbatim_through_the_port()
{
await using var origin = new RealOrigin();
origin.History!.Samples = [new(1.5, 0x00000400u, T0.UtcDateTime, null), new(null, 0x80000000u, null, T0.AddSeconds(1).UtcDateTime)];
var response = await origin.HistoryAsync(Raw(I("flow", RealOriginRequests.Flow), I("ref", RealOriginRequests.UnsFlow)), History);
response.Serving.ShouldNotBeNull();
foreach (var item in response.Items)
{
item.StatusCode.ShouldBe(0u);
item.Samples.Count.ShouldBe(2);
item.Samples[0].Value.DoubleValue.ShouldBe(1.5);
item.Samples[0].StatusCode.ShouldBe(0x400u);
item.Samples[0].ServerTimestamp.ShouldBeNull();
item.Samples[1].SourceTimestamp.ShouldBeNull();
item.Samples[1].StatusCode.ShouldBe(0x80000000u);
}
origin.History.LastItems.Select(x => (x.Realm, x.Identifier)).ShouldBe(
[(AddressSpaceRealm.Raw, "Plant/Modbus/dev1/Flow"), (AddressSpaceRealm.Uns, "Area1/Line1/Filler/FlowRate")]);
var raw = origin.History.LastDetails.ShouldBeOfType<DataHistoryRawDetails>();
raw.NumValuesPerNode.ShouldBe(10_000u, "an uncapped read pages at the export's per-page ceiling");
raw.StartUtc.ShouldBe(T0);
}
[Fact]
public async Task A_value_kind_disagreeing_with_the_catalog_is_BadTypeMismatch()
{
await using var origin = new RealOrigin();
origin.History!.Samples = [new("not a double", 0, T0.UtcDateTime, null), new(2.0, 0, T0.UtcDateTime, null)];
var item = (await origin.HistoryAsync(Raw(I("flow", RealOriginRequests.Flow)), History)).Items.Single();
item.Samples[0].StatusCode.ShouldBe(DataHistoryProtoMapper.BadTypeMismatch);
item.Samples[0].Value.Kind.ShouldBe(W.ValueKind.Null);
item.Samples[1].Value.DoubleValue.ShouldBe(2.0);
}
[Fact]
public async Task Admission_past_MaxConcurrentHistoryReads_is_BadTooManyOperations_for_the_principal()
{
await using var origin = new RealOrigin(concurrentReads: 1);
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
origin.History!.Hold = gate.Task;
var first = origin.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History);
await origin.History.Entered.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
var second = await origin.HistoryAsync(Raw(I("b", RealOriginRequests.Flow), I("c", RealOriginRequests.Speed)), History, "conn-2");
second.Items.Select(x => x.StatusCode).ShouldBe([0x80100000u, 0x80100000u]);
gate.SetResult();
(await first).Items.Single().StatusCode.ShouldBe(0u);
// Admission is released: the next read is served.
(await origin.HistoryAsync(Raw(I("d", RealOriginRequests.Flow)), History)).Items.Single().StatusCode.ShouldBe(0u);
}
[Fact]
public async Task A_caller_cancel_is_Cancelled_never_a_backend_outcome_and_releases_admission()
{
await using var origin = new RealOrigin(concurrentReads: 1);
origin.History!.Hold = new TaskCompletionSource().Task; // never completes on its own; the token ends it
using var cancel = new CancellationTokenSource();
var read = origin.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History, cancel: cancel);
await origin.History.Entered.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
await cancel.CancelAsync();
var failure = await Should.ThrowAsync<RpcException>(() => read);
failure.StatusCode.ShouldBe(StatusCode.Cancelled);
origin.History.Hold = null;
(await origin.HistoryAsync(Raw(I("b", RealOriginRequests.Flow)), History)).Items.Single().StatusCode.ShouldBe(0u);
}
[Fact]
public async Task A_wiring_fault_is_BadInternalError_with_a_distinct_diagnostic()
{
await using var origin = new RealOrigin();
origin.History!.WiringFault = true;
var item = (await origin.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History)).Items.Single();
item.StatusCode.ShouldBe(0x80020000u);
item.Diagnostic.ShouldContain("wiring");
item.StatusCode.ShouldNotBe(0x80720000u);
}
[Fact]
public async Task An_answer_larger_than_the_response_cap_is_chunked_and_a_lost_chunk_is_ContinuationPointInvalid()
{
await using var origin = new RealOrigin(responseBytes: 1);
origin.History!.Samples = Enumerable.Range(0, 2000).Select(i => new OriginHistorySample((double)i, 0, T0.AddSeconds(i).UtcDateTime, null)).ToArray();
origin.History.Continuation = Enumerable.Repeat((byte)7, 16).ToArray();
var request = Raw(I("a", RealOriginRequests.Flow));
var all = new List<double>();
var page = (await origin.HistoryAsync(request, History)).Items.Single();
var chunks = 1;
page.ChunkContinues.ShouldBeTrue();
var firstToken = page.Continuation.ToByteArray();
while (page.ChunkContinues)
{
all.AddRange(page.Samples.Select(s => s.Value.DoubleValue));
var next = request.Clone(); next.Items[0].Continuation = page.Continuation;
page = (await origin.HistoryAsync(next, History)).Items.Single();
chunks++;
}
all.AddRange(page.Samples.Select(s => s.Value.DoubleValue));
chunks.ShouldBeGreaterThan(1);
all.ShouldBe(Enumerable.Range(0, 2000).Select(i => (double)i));
page.Continuation.ToByteArray().ShouldBe(origin.History.Continuation, "the last chunk carries the page continuation");
origin.History.Calls.ShouldBe(1, "chunks are served from the transport remainder, not re-read");
// The first chunk token was consumed: replaying it (a page lost in transit) is invalid, never a skipped page.
var replay = request.Clone(); replay.Items[0].Continuation = ByteString.CopyFrom(firstToken);
(await origin.HistoryAsync(replay, History)).Items.Single().StatusCode.ShouldBe(0x804A0000u);
// Another HTTP/2 connection cannot use this connection's tokens.
var fresh = (await origin.HistoryAsync(request, History, "conn-a")).Items.Single();
var stolen = request.Clone(); stolen.Items[0].Continuation = fresh.Continuation;
(await origin.HistoryAsync(stolen, History, "conn-b")).Items.Single().StatusCode.ShouldBe(0x804A0000u);
}
[Fact]
public async Task Release_continuations_drops_the_tokens_without_reading()
{
await using var origin = new RealOrigin(responseBytes: 1);
origin.History!.Samples = Enumerable.Range(0, 2000).Select(i => new OriginHistorySample((double)i, 0, T0.AddSeconds(i).UtcDateTime, null)).ToArray();
var request = Raw(I("a", RealOriginRequests.Flow));
var chunk = (await origin.HistoryAsync(request, History)).Items.Single();
chunk.ChunkContinues.ShouldBeTrue();
var release = request.Clone(); release.Items[0].Continuation = chunk.Continuation; release.ReleaseContinuations = true;
var released = (await origin.HistoryAsync(release, History)).Items.Single();
released.StatusCode.ShouldBe(0u); released.Samples.ShouldBeEmpty();
origin.History.Calls.ShouldBe(1);
var resume = request.Clone(); resume.Items[0].Continuation = chunk.Continuation;
(await origin.HistoryAsync(resume, History)).Items.Single().StatusCode.ShouldBe(0x804A0000u);
}
[Fact]
public async Task Direct_runtime_consumer_reads_history_through_the_local_connection_unchunked()
{
await using var origin = new RealOrigin(responseBytes: 1);
origin.History!.Samples = Enumerable.Range(0, 500).Select(i => new OriginHistorySample((double)i, 0, T0.AddSeconds(i).UtcDateTime, null)).ToArray();
await using var connection = origin.Connect();
var history = connection.ShouldBeAssignableTo<IDataHistoryService>()!;
var results = await history.ReadAsync(new DataHistoryReadRequest(new DataHistoryRawDetails(null, T0.AddHours(1), 0, false),
[I("a", RealOriginRequests.Flow), I("b", RealOriginRequests.Speed)], Budget), TestContext.Current.CancellationToken);
results[0].ChunkContinues.ShouldBeFalse("a direct consumer is never handed transport chunks");
results[0].Samples.Count.ShouldBe(500);
results[0].Samples[0].SourceTimestampUtc.ShouldBe(T0);
results[1].StatusCode.ShouldBe(0x80720000u);
origin.History.LastDetails.ShouldBeOfType<DataHistoryRawDetails>().StartUtc.ShouldBeNull("absent stays absent end to end");
foreach (var result in results) result.Dispose();
}
[Fact]
public async Task Every_rpc_records_history_effective_only_when_the_origin_can_serve_it()
{
await using var origin = new RealOrigin();
var context = RealOrigin.NewContext("HistoryRead", History, TestContext.Current.CancellationToken);
await origin.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History, existing: context);
DataConnectionGrpcService.CallFeatures(context).ShouldBe(new DataCallFeatures(DataFeatures.History, DataFeatures.History));
await using var none = new RealOrigin(historian: false);
var refused = RealOrigin.NewContext("HistoryRead", History, TestContext.Current.CancellationToken);
await Should.ThrowAsync<RpcException>(() => none.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History, existing: refused));
DataConnectionGrpcService.CallFeatures(refused).ShouldBe(new DataCallFeatures(DataFeatures.History, DataFeatures.None));
}
}
/// <summary>A scripted node-manager history port: Flow (raw) and FlowRate (UNS) are historized.</summary>
internal sealed class FakeHistoryPort : IOriginHistoryPort
{
private int _calls, _lookups;
private readonly TaskCompletionSource _entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly ConcurrentDictionary<string, bool> _issued = new();
public OriginHistoryServing? Serving { get; set; } = new(["Average", "Count"], 10);
public IReadOnlyList<OriginHistorySample> Samples { get; set; } = [];
public byte[]? Continuation { get; set; }
public bool WiringFault { get; set; }
public Task? Hold { get; set; }
public Task Entered => _entered.Task;
public int Calls => Volatile.Read(ref _calls);
public int HistorizedLookups => Volatile.Read(ref _lookups);
public IReadOnlyList<OriginHistoryItem> LastItems { get; private set; } = [];
public DataHistoryDetails? LastDetails { get; private set; }
public bool IsHistorized(AddressSpaceRealm realm, string identifier)
{
Interlocked.Increment(ref _lookups);
return (realm == AddressSpaceRealm.Raw && identifier == "Plant/Modbus/dev1/Flow")
|| (realm == AddressSpaceRealm.Uns && identifier == "Area1/Line1/Filler/FlowRate");
}
public async Task<IReadOnlyList<OriginHistoryOutcome>> ReadAsync(OriginHistoryCursors cursors, string principal, Func<string> servingIncarnation,
DataHistoryDetails details, IReadOnlyList<OriginHistoryItem> items, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _calls);
LastItems = items; LastDetails = details;
_entered.TrySetResult();
if (Hold is { } hold) await hold.WaitAsync(cancellationToken);
await Task.Yield();
// Emulates the real port's single-use store: an unknown/consumed token is BadContinuationPointInvalid.
return items.Select(item =>
{
if (WiringFault) return new OriginHistoryOutcome(0x80020000u, [], null, true);
if (item.Continuation is { } token && !_issued.TryRemove(Convert.ToHexString(token), out _))
return new OriginHistoryOutcome(0x804A0000u, [], null, false);
if (Continuation is { } next) _issued[Convert.ToHexString(next)] = true;
return new OriginHistoryOutcome(0, Samples, Continuation, false);
}).ToArray();
}
}