Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs
T
Joseph Doherty a3da73e1e7 fix(grpc-data): H2 review2-2..6 - byte-bounded pages, one deadline, no leaked cursors
Each node's Raw page is clamped from a per-value byte estimate of its catalog type (wide strings/arrays get small
pages plus a continuation) and sub-batches are sized by estimated bytes, so the in-flight read respects
MaxHistoryResponseBytes; AtTime/Processed whose values x estimate exceed the budget are refused per node with a
diagnostic. One deadline per request: nodes not started when it passes are deferred (transport) or BadTimeout
(direct). Every refusal releases the page cursor it was just given; releasing, invalidating or expiring a chunk
releases the page cursor behind it; results are disposed on the exception path. Chunk bindings use per-node details.
OpcUaServer IVT for Runtime.Tests/Host.Tests so tests can hold real page cursors.
2026-11-23 23:16:14 -05:00

525 lines
33 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.AllItems.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));
}
[Fact]
public async Task A_not_ready_or_demoted_history_capable_origin_answers_Unavailable_not_FailedPrecondition()
{
// Negotiation = header ∩ supported ∩ origin-has-historian; readiness is Ready()'s job, so the client fails over like v1.
await using var demoted = new RealOrigin(role: "Secondary");
var failure = await Should.ThrowAsync<RpcException>(() => demoted.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History));
failure.StatusCode.ShouldBe(StatusCode.Unavailable);
var probe = W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(await demoted.DriveAsync("GetCapabilities", History)));
probe.History.ShouldNotBeNull("the historian is there; the node is just not ready for this target");
probe.Readiness.ShouldBe((int)DataReadiness.Unavailable);
// An origin whose export grants no HistoryRead to this peer is PermissionDenied, as v1 Read is without a Read grant.
await using var ungranted = new RealOrigin(exportOperations: DataOperationSets.V1, grantHistory: false);
var denied = await Should.ThrowAsync<RpcException>(() => ungranted.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History));
denied.StatusCode.ShouldBe(StatusCode.PermissionDenied);
}
[Fact]
public async Task A_v1_metadata_call_does_not_rebuild_the_history_view_per_node_and_operation()
{
await using var origin = new RealOrigin();
var before = origin.History!.ServingReads;
var lookups = origin.History.HistorizedLookups;
await origin.DriveAsync("GetMetadata", new Metadata()); // 11 views, header-less
(origin.History.ServingReads - before).ShouldBeLessThanOrEqualTo(16, "at most about one per node, not one per node and operation");
(origin.History.HistorizedLookups - lookups).ShouldBeLessThanOrEqualTo(11);
}
[Fact]
public async Task Origin_memory_is_bounded_per_request_and_per_principal_and_nothing_is_lost()
{
await using var origin = new RealOrigin(responseBytes: 256 * 1024, valuesPerPage: 2000);
origin.History!.SamplesPerItem = 2000;
var request = DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest(new DataHistoryRawDetails(T0, T0.AddHours(1), 0, false),
Enumerable.Range(0, 100).Select(i => I("i" + i, RealOriginRequests.Flow)).ToArray(), Budget with { MaxItems = 100 }));
var first = await origin.HistoryAsync(request, History);
first.CalculateSize().ShouldBeLessThanOrEqualTo(256 * 1024);
// Only what the response budget can carry (plus at most one sub-batch) was read; the rest is deferred, unread.
origin.History.ValuesReturned.ShouldBeLessThanOrEqualTo(10 * 2000);
first.Items.Count(x => x.ChunkContinues && x.Samples.Count == 0).ShouldBeGreaterThan(80, "most nodes deferred, not materialised");
var retainedBudget = 4L * Math.Max(256 * 1024 - 64 * 1024, 2000L * 64);
origin.Services.HistoryRetainedBytes("peer").ShouldBeLessThanOrEqualTo(retainedBudget);
// Following every chunk token delivers every value exactly once.
var counts = new long[100];
var page = first;
var rounds = 0;
while (true)
{
var next = request.Clone(); next.Items.Clear();
for (var k = 0; k < page.Items.Count; k++)
{
var item = page.Items[k];
var index = int.Parse(item.CorrelationId[1..], System.Globalization.CultureInfo.InvariantCulture);
item.StatusCode.ShouldBe(0u);
counts[index] += item.Samples.Count;
if (item.ChunkContinues) next.Items.Add(new W.HistoryReadItem { CorrelationId = item.CorrelationId, View = request.Items[index].View, Continuation = item.Continuation });
}
origin.Services.HistoryRetainedBytes("peer").ShouldBeLessThanOrEqualTo(retainedBudget);
if (next.Items.Count == 0) break;
page = await origin.HistoryAsync(next, History);
page.CalculateSize().ShouldBeLessThanOrEqualTo(256 * 1024);
(++rounds).ShouldBeLessThan(500);
}
counts.ShouldAllBe(c => c == 2000);
origin.Services.HistoryRetainedBytes("peer").ShouldBe(0, "every remainder was taken");
}
[Fact]
public async Task Wide_values_get_a_byte_sized_page_so_in_flight_bytes_respect_the_response_budget()
{
await using var origin = new RealOrigin(responseBytes: 256 * 1024, valuesPerPage: 10_000);
origin.History!.AlsoHistorized.Add("Plant/Modbus/dev1/Label");
origin.History.SamplesPerItem = 10_000;
origin.History.ValueFactory = i => new string('w', 900);
origin.History.Continuation = [5, 5, 5];
var request = DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest(new DataHistoryRawDetails(T0, T0.AddHours(1), 0, false),
Enumerable.Range(0, 20).Select(i => I("w" + i, RealOriginRequests.Label)).ToArray(), Budget with { MaxItems = 100 }));
var response = await origin.HistoryAsync(request, History);
response.CalculateSize().ShouldBeLessThanOrEqualTo(256 * 1024);
// Budget 192 KiB at a 1 KiB estimate per string ⇒ a page of ~190 values; never the 10,000 a narrow tag would get.
origin.History.MaxCallBytes.ShouldBeLessThanOrEqualTo(256 * 1024, "the in-flight sub-batch respects the response budget");
var first = response.Items[0];
first.StatusCode.ShouldBe(0u, "a wide tag stays readable");
(first.Samples.Count > 0 || first.ChunkContinues).ShouldBeTrue();
response.Items.ShouldAllBe(x => x.StatusCode == 0u);
}
[Fact]
public async Task Processed_intervals_and_AtTime_times_above_the_page_ceiling_are_refused_unsent()
{
await using var origin = new RealOrigin(valuesPerPage: 2000);
var processed = DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest(
new DataHistoryProcessedDetails(T0, T0.AddHours(1), TimeSpan.FromSeconds(1), null),
[new("a", RealOriginRequests.Flow, DataHistoryAggregates.IdByName["Average"])], Budget));
(await origin.HistoryAsync(processed, History)).Items.Single().StatusCode.ShouldBe(0x80100000u);
var times = Enumerable.Range(0, 2001).Select(i => T0.AddSeconds(i)).ToArray();
var atTime = DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest(new DataHistoryAtTimeDetails(times),
[I("a", RealOriginRequests.Flow), I("b", RealOriginRequests.UnsFlow)], Budget));
(await origin.HistoryAsync(atTime, History)).Items.Select(x => x.StatusCode).ShouldBe([0x80100000u, 0x80100000u]);
origin.History!.Calls.ShouldBe(0);
// Within the ceiling the same shapes are served.
var within = DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest(
new DataHistoryProcessedDetails(T0, T0.AddHours(1), TimeSpan.FromSeconds(2), null),
[new("a", RealOriginRequests.Flow, DataHistoryAggregates.IdByName["Average"])], Budget));
(await origin.HistoryAsync(within, History)).Items.Single().StatusCode.ShouldBe(0u);
}
[Fact]
public async Task A_single_value_larger_than_the_response_limit_is_answered_per_item()
{
await using var origin = new RealOrigin(responseBytes: 1);
origin.History!.AlsoHistorized.Add("Plant/Modbus/dev1/Label");
origin.History.Samples = [new(new string('x', 40_000), 0, T0.UtcDateTime, null)];
var response = await origin.HistoryAsync(Raw(I("label", RealOriginRequests.Label)), History);
var item = response.Items.Single();
item.StatusCode.ShouldBe(0x80100000u);
item.Diagnostic.ShouldContain("exceeds");
item.Samples.ShouldBeEmpty();
}
[Fact]
public async Task A_refused_node_releases_the_page_cursor_it_was_just_given()
{
await using var origin = new RealOrigin(responseBytes: 1);
origin.History!.AlsoHistorized.Add("Plant/Modbus/dev1/Label");
origin.History.RealCursors = true; // the fake saves a REAL page cursor in the session's store and returns its token
origin.History.Samples = [new(new string('x', 40_000), 0, T0.UtcDateTime, null)];
var item = (await origin.HistoryAsync(Raw(I("label", RealOriginRequests.Label)), History)).Items.Single();
item.StatusCode.ShouldBe(0x80100000u);
origin.History.LastCursors.ShouldNotBeNull().Count.ShouldBe(0, "the refused node's page cursor is not left behind");
}
[Fact]
public async Task The_request_has_one_deadline_and_nodes_not_started_before_it_are_deferred_or_BadTimeout()
{
await using var origin = new RealOrigin(valuesPerPage: 10_000);
origin.History!.SamplesPerItem = 1;
origin.History.DelayPerCall = TimeSpan.FromMilliseconds(250);
var items = Enumerable.Range(0, 40).Select(i => I("i" + i, RealOriginRequests.Flow)).ToArray();
var budget = Budget with { MaxItems = 100, Timeout = TimeSpan.FromMilliseconds(400) };
// Transport: unread nodes come back as deferred chunk tokens.
var response = await origin.HistoryAsync(DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest(
new DataHistoryRawDetails(T0, T0.AddHours(1), 0, false), items, budget)), History);
response.Items.Count(x => x.ChunkContinues && x.Samples.Count == 0).ShouldBeGreaterThan(0, "nodes not started before the deadline are deferred");
origin.History.Calls.ShouldBeLessThan(6, "no sub-batch starts after the request's single deadline");
// Direct consumer: the same nodes are BadTimeout.
await using var connection = origin.Connect();
var results = await ((IDataHistoryService)connection).ReadAsync(new DataHistoryReadRequest(
new DataHistoryRawDetails(T0, T0.AddHours(1), 0, false), items, budget), TestContext.Current.CancellationToken);
results.Count(x => x.StatusCode == 0x800A0000u).ShouldBeGreaterThan(0);
results.ShouldAllBe(x => !x.ChunkContinues);
foreach (var r in results) r.Dispose();
}
[Fact]
public async Task A_direct_consumer_gets_BadTooManyOperations_for_nodes_past_its_request_budget()
{
await using var origin = new RealOrigin(valuesPerPage: 2000);
origin.History!.SamplesPerItem = 2000;
await using var connection = origin.Connect();
var history = (IDataHistoryService)connection;
var results = await history.ReadAsync(new DataHistoryReadRequest(new DataHistoryRawDetails(T0, T0.AddHours(1), 0, false),
Enumerable.Range(0, 50).Select(i => I("i" + i, RealOriginRequests.Flow)).ToArray(), Budget with { MaxItems = 100, MaxBytes = 64 * 1024 }),
TestContext.Current.CancellationToken);
results[0].Samples.Count.ShouldBeInRange(1, 64 * 1024 / 56, "the page is clamped to what the request budget can carry");
results.Last().StatusCode.ShouldBe(0x80100000u);
results.ShouldAllBe(r => !r.ChunkContinues);
origin.History.ValuesReturned.ShouldBeLessThanOrEqualTo(10 * 2000);
foreach (var r in results) r.Dispose();
}
}
/// <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();
private OriginHistoryServing? _serving = new(["Average", "Count"], 10);
private int _servingReads;
public OriginHistoryServing? Serving { get { Interlocked.Increment(ref _servingReads); return _serving; } set => _serving = value; }
/// <summary>How often the origin asked what it can serve.</summary>
public int ServingReads => Volatile.Read(ref _servingReads);
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; } = [];
private readonly List<OriginHistoryItem> _all = [];
/// <summary>Every item the port was asked for, across calls (the origin reads in sub-batches).</summary>
public IReadOnlyList<OriginHistoryItem> AllItems { get { lock (_all) return _all.ToArray(); } }
public DataHistoryDetails? LastDetails { get; private set; }
/// <summary>When set, each item gets min(this, the page cap) generated values instead of <see cref="Samples"/>.</summary>
public int? SamplesPerItem { get; set; }
/// <summary>Generated value i (default: the double i).</summary>
public Func<int, object?>? ValueFactory { get; set; }
/// <summary>Save a real page cursor in the passed store for each answer (instead of <see cref="Continuation"/>).</summary>
public bool RealCursors { get; set; }
/// <summary>Each call waits this long (honouring the call's token) before answering.</summary>
public TimeSpan? DelayPerCall { get; set; }
/// <summary>The cursor store of the last call.</summary>
public OriginHistoryCursors? LastCursors { get; private set; }
/// <summary>The largest approximate payload one port call materialised.</summary>
public long MaxCallBytes { get; private set; }
/// <summary>Values handed out by the port in total (the origin materialised at most this many).</summary>
public long ValuesReturned => Interlocked.Read(ref _values);
/// <summary>Further historized raw identifiers.</summary>
public HashSet<string> AlsoHistorized { get; } = [];
private long _values;
public bool IsHistorized(AddressSpaceRealm realm, string identifier)
{
Interlocked.Increment(ref _lookups);
return (realm == AddressSpaceRealm.Raw && (identifier == "Plant/Modbus/dev1/Flow" || AlsoHistorized.Contains(identifier)))
|| (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; LastCursors = cursors;
lock (_all) _all.AddRange(items);
_entered.TrySetResult();
if (Hold is { } hold) await hold.WaitAsync(cancellationToken);
if (DelayPerCall is { } delay) await Task.Delay(delay, cancellationToken);
await Task.Yield();
// Emulates the real port's single-use store: an unknown/consumed token is BadContinuationPointInvalid.
long callBytes = 0;
var outcomes = 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;
IReadOnlyList<OriginHistorySample> samples = Samples;
if (SamplesPerItem is { } count)
{
var cap = details is DataHistoryRawDetails { NumValuesPerNode: > 0 } raw ? (int)Math.Min(raw.NumValuesPerNode, (uint)count) : count;
samples = Enumerable.Range(0, cap).Select(i => new OriginHistorySample(ValueFactory?.Invoke(i) ?? (double)i, 0, DateTime.UnixEpoch.AddSeconds(i), null)).ToArray();
}
Interlocked.Add(ref _values, samples.Count);
foreach (var x in samples) callBytes += 48 + (x.Value is string text ? text.Length : 16);
var page = RealCursors ? cursors.Store.Save(new ZB.MOM.WW.OtOpcUa.OpcUaServer.HistoryContinuationState("t", DateTime.UnixEpoch,
DateTime.UnixEpoch, 0, 1) { BoundIdentifier = item.Identifier }, principal, "inc", "h") : Continuation;
return new OriginHistoryOutcome(0, samples, page, false);
}).ToArray();
lock (_all) MaxCallBytes = Math.Max(MaxCallBytes, callBytes);
return outcomes;
}
}