Files
lmxopcua/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataHistoryCodecTests.cs
T
Joseph Doherty 619b0c378d feat(grpc-data): H2 history wire contract and codecs; HistoryRead understood
HistoryRead rpc + HistoryCapabilities (16) / HistoryInfo (14) per plan 4.2; DataHistoryProtoMapper keeps the full
uint32 status, ns Timestamps, absent start/end/sample timestamps, verbatim aggregate configuration, and BadTypeMismatch
for a value kind disagreeing with the catalog. DataOperationSets.Understood gains HistoryRead; X0 tripwire replaced.
2026-11-23 20:33:26 -05:00

213 lines
13 KiB
C#

using Google.Protobuf;
using Google.Protobuf.Reflection;
using Google.Protobuf.WellKnownTypes;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Commons.Protos;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.DataConnections;
/// <summary>H2 remote-history codecs (plan §4.2, §3.3 fidelity).</summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H2")]
public sealed class GrpcDataHistoryCodecTests
{
private static readonly DataView View = new(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/Speed"),
DataRealm.Raw, null, 0, "Plant/Speed");
private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 16, 1 << 20);
[Fact]
public void The_reserved_numbers_now_carry_their_planned_fields_and_the_rpc_exists()
{
var caps = W.CapabilitiesResponse.Descriptor.FindFieldByNumber(16).ShouldNotBeNull();
caps.Name.ShouldBe("history"); caps.FieldType.ShouldBe(FieldType.Message); caps.MessageType.Name.ShouldBe("HistoryCapabilities");
var meta = W.Metadata.Descriptor.FindFieldByNumber(14).ShouldNotBeNull();
meta.Name.ShouldBe("history"); meta.FieldType.ShouldBe(FieldType.Message); meta.MessageType.Name.ShouldBe("HistoryInfo");
var methods = W.DataConnectionReflection.Descriptor.Services.Single().Methods;
methods.Count.ShouldBe(7);
var rpc = methods.Single(m => m.Name == "HistoryRead");
rpc.InputType.Name.ShouldBe("HistoryReadRequest"); rpc.OutputType.Name.ShouldBe("HistoryReadResponse");
rpc.IsClientStreaming.ShouldBeFalse(); rpc.IsServerStreaming.ShouldBeFalse();
// §4.2 field numbers.
W.HistoryReadRequest.ItemsFieldNumber.ShouldBe(1); W.HistoryReadRequest.BudgetFieldNumber.ShouldBe(2);
W.HistoryReadRequest.RawFieldNumber.ShouldBe(3); W.HistoryReadRequest.ProcessedFieldNumber.ShouldBe(4);
W.HistoryReadRequest.AtTimeFieldNumber.ShouldBe(5); W.HistoryReadRequest.ReleaseContinuationsFieldNumber.ShouldBe(6);
W.HistoryReadResult.ContinuationFieldNumber.ShouldBe(4); W.HistoryReadResult.ChunkContinuesFieldNumber.ShouldBe(6);
W.HistorySample.SourceTimestampFieldNumber.ShouldBe(3); W.HistorySample.ServerTimestampFieldNumber.ShouldBe(4);
W.ProcessedDetails.ConfigurationFieldNumber.ShouldBe(5); W.AtTimeDetails.UseSimpleBoundsFieldNumber.ShouldBe(2);
Should.NotThrow(DataConnectionProtoContract.Validate);
}
[Theory]
[InlineData(0x00000000u)] // Good
[InlineData(0x00A50000u)] // GoodNoData
[InlineData(0x80A50000u)] // BadNoData
[InlineData(0x80EA0000u)] // Bad_BoundNotFound
[InlineData(0x40A40000u | 0x400 | 0x200)] // UncertainDataSubNormal + Calculated + Partial info bits
[InlineData(0x00000000u | 0x400 | 0x100)] // Good + Calculated + Interpolated-ish bits
[InlineData(0xFFFFFFFFu)] // every bit
public void The_full_uint32_status_passes_through_on_samples_and_results(uint status)
{
using var result = new DataHistoryReadResult("c", status, [Sample(status, At(0), At(1))], null);
using var decoded = RoundTrip(result);
decoded.StatusCode.ShouldBe(status);
decoded.Samples.Single().StatusCode.ShouldBe(status);
}
[Fact]
public void An_absent_sample_timestamp_stays_absent_and_never_becomes_MinValue()
{
using var result = new DataHistoryReadResult("c", 0, [Sample(0, null, null), Sample(0, At(5), null), Sample(0, null, At(6))], null);
var wire = DataHistoryProtoMapper.EncodeResult(result);
wire.Samples[0].SourceTimestamp.ShouldBeNull(); wire.Samples[0].ServerTimestamp.ShouldBeNull();
using var decoded = RoundTrip(result);
decoded.Samples[0].SourceTimestampUtc.ShouldBeNull(); decoded.Samples[0].ServerTimestampUtc.ShouldBeNull();
decoded.Samples[1].SourceTimestampUtc.ShouldBe(At(5)); decoded.Samples[1].ServerTimestampUtc.ShouldBeNull();
decoded.Samples[2].SourceTimestampUtc.ShouldBeNull(); decoded.Samples[2].ServerTimestampUtc.ShouldBe(At(6));
}
[Fact]
public void Timestamps_keep_100ns_precision_and_finer_than_a_tick_is_refused()
{
var precise = new DateTimeOffset(2026, 11, 23, 12, 0, 0, TimeSpan.Zero).AddTicks(1_234_567);
using var result = new DataHistoryReadResult("c", 0, [Sample(0, precise, precise.AddTicks(1))], null);
using var decoded = RoundTrip(result);
decoded.Samples[0].SourceTimestampUtc.ShouldBe(precise);
decoded.Samples[0].ServerTimestampUtc.ShouldBe(precise.AddTicks(1));
var wire = DataHistoryProtoMapper.EncodeResult(result);
wire.Samples[0].SourceTimestamp.Value.Nanos.ShouldBe(123_456_700);
wire.Samples[0].SourceTimestamp.Value = new Timestamp { Seconds = wire.Samples[0].SourceTimestamp.Value.Seconds, Nanos = 123_456_701 };
Should.Throw<ArgumentException>(() => DataHistoryProtoMapper.DecodeResult(wire));
}
[Theory]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false)]
public void Absent_start_and_end_stay_absent_for_raw_and_processed(bool hasStart, bool hasEnd)
{
DateTimeOffset? start = hasStart ? At(1) : null, end = hasEnd ? At(9) : null;
var raw = Decode(new DataHistoryReadRequest(new DataHistoryRawDetails(start, end, 7, true), [new("a", View)], Budget));
raw.Details.ShouldBe(new DataHistoryRawDetails(start, end, 7, true));
var encoded = DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest(new DataHistoryRawDetails(start, end, 7, true), [new("a", View)], Budget));
encoded.Raw.Start.ShouldBe(hasStart ? Timestamp.FromDateTimeOffset(At(1)) : null);
encoded.Raw.End.ShouldBe(hasEnd ? Timestamp.FromDateTimeOffset(At(9)) : null);
var processed = Decode(new DataHistoryReadRequest(new DataHistoryProcessedDetails(start, end, TimeSpan.FromMinutes(1), null),
[new("a", View, DataHistoryAggregates.IdByName["Average"])], Budget));
var details = processed.Details.ShouldBeOfType<DataHistoryProcessedDetails>();
details.StartUtc.ShouldBe(start); details.EndUtc.ShouldBe(end);
details.Configuration.ShouldBeNull("an absent configuration stays absent (server defaults)");
}
[Fact]
public void Aggregate_configuration_and_aggregates_pass_through_verbatim()
{
var configuration = new DataAggregateConfiguration(false, true, 37, 61, true);
var decoded = Decode(new DataHistoryReadRequest(new DataHistoryProcessedDetails(At(0), At(100), TimeSpan.FromTicks(12_345), configuration),
[new("a", View, 2342), new("b", View, 11304), new("c", View, 999_999)], Budget));
var details = decoded.Details.ShouldBeOfType<DataHistoryProcessedDetails>();
details.Configuration.ShouldBe(configuration);
details.ProcessingInterval.ShouldBe(TimeSpan.FromTicks(12_345));
decoded.Items[0].AggregateId.ShouldBe(2342u);
decoded.Items[1].AggregateId.ShouldBe(11304u);
// An id this build cannot name travels as i=<id> and decodes to "no aggregate" — the origin refuses it.
DataHistoryAggregates.NameOf(999_999).ShouldBe("i=999999");
decoded.Items[2].AggregateId.ShouldBe(DataHistoryProtoMapper.UnknownAggregate);
}
[Fact]
public void AtTime_times_order_and_simple_bounds_round_trip()
{
var times = new[] { At(3), At(1), At(2).AddTicks(7) };
var decoded = Decode(new DataHistoryReadRequest(new DataHistoryAtTimeDetails(times, true), [new("a", View)], Budget));
var details = decoded.Details.ShouldBeOfType<DataHistoryAtTimeDetails>();
details.RequestedTimesUtc.ShouldBe(times);
details.UseSimpleBounds.ShouldBeTrue();
}
[Fact]
public void Continuation_release_flag_and_chunk_continues_round_trip()
{
var token = Enumerable.Range(0, 16).Select(i => (byte)i).ToArray();
var request = new DataHistoryReadRequest(new DataHistoryRawDetails(null, At(1), 0, false), [new("a", View, null, token)], Budget);
var (decoded, release) = DataHistoryProtoMapper.DecodeRequest(W.HistoryReadRequest.Parser.ParseFrom(
DataHistoryProtoMapper.EncodeRequest(request, releaseContinuations: true).ToByteArray()));
release.ShouldBeTrue();
decoded.Items[0].Continuation.ShouldBe(token);
using var chunk = new DataHistoryReadResult("a", 0, [], token, "chunk", ChunkContinues: true);
using var back = RoundTrip(chunk);
back.ChunkContinues.ShouldBeTrue(); back.Continuation.ShouldBe(token); back.Diagnostic.ShouldBe("chunk");
var bad = DataHistoryProtoMapper.EncodeResult(chunk); bad.ClearContinuation();
Should.Throw<ArgumentException>(() => DataHistoryProtoMapper.DecodeResult(bad));
}
[Fact]
public void A_value_kind_that_disagrees_with_the_catalog_is_BadTypeMismatch_never_coerced()
{
var catalog = new DataMetadata(View, "Speed", "Variable", DataValueKind.Int32, -1, [], false, DataOperations.Read, 1, null, null, false);
using var result = new DataHistoryReadResult("c", 0,
[new(DataValue.FromScalar(DataValueKind.Double, 1.5), 0, At(1), null), new(DataValue.FromScalar(DataValueKind.Int32, 4), 0, At(2), null),
new(DataValue.Null(), 0x80000000u, At(3), null)], null);
var wire = DataHistoryProtoMapper.EncodeResult(result, catalog);
wire.Samples[0].StatusCode.ShouldBe(DataHistoryProtoMapper.BadTypeMismatch);
wire.Samples[0].Value.Kind.ShouldBe(W.ValueKind.Null);
wire.Samples[1].StatusCode.ShouldBe(0u); wire.Samples[1].Value.Signed.ShouldBe(4);
wire.Samples[2].StatusCode.ShouldBe(0x80000000u, "a null value always matches");
// The decoder applies the same rule when the receiver knows the catalog.
var original = DataHistoryProtoMapper.EncodeResult(result);
using var decoded = DataHistoryProtoMapper.DecodeResult(original, null, catalog);
decoded.Samples[0].StatusCode.ShouldBe(DataHistoryProtoMapper.BadTypeMismatch);
decoded.Samples[0].Value.Kind.ShouldBe(DataValueKind.Null);
decoded.Samples[1].Value.GetScalar().ShouldBe(4);
}
[Fact]
public void Capabilities_and_metadata_history_round_trip_and_invalid_advertisements_are_ignored()
{
var history = new DataHistoryCapabilities(true, true, true, ["Average", "Count"], 10, 10_000, 4, TimeSpan.FromSeconds(60));
var wire = DataHistoryProtoMapper.EncodeCapabilities(history);
var decoded = DataHistoryProtoMapper.DecodeCapabilities(W.HistoryCapabilities.Parser.ParseFrom(wire.ToByteArray()));
decoded.ShouldNotBeNull();
decoded!.Aggregates.ShouldBe(["Average", "Count"]);
(decoded with { Aggregates = history.Aggregates }).ShouldBe(history);
DataHistoryProtoMapper.DecodeCapabilities(new W.HistoryCapabilities { Raw = true }).ShouldBeNull("zero limits are not a usable advertisement");
DataHistoryProtoMapper.DecodeCapabilities(null).ShouldBeNull();
var metadata = new DataMetadata(View, "Speed", "Variable", DataValueKind.Int32, -1, [], false,
DataOperations.Read | DataOperations.HistoryRead, 1, null, null, false, History: new DataHistoryInfo(true));
var encoded = DataProtoMapper.EncodeMetadata(metadata);
encoded.History.Historizing.ShouldBeTrue();
encoded.AllowedOperations.ShouldBe((uint)(DataOperations.Read | DataOperations.HistoryRead));
var back = DataProtoMapper.DecodeMetadata(encoded);
back.History.ShouldBe(new DataHistoryInfo(true));
back.AllowedOperations.ShouldBe(DataOperations.Read | DataOperations.HistoryRead, "H2 understands bit 32");
}
[Fact]
public void Requests_are_bounded_by_the_receiver_limits()
{
var items = Enumerable.Range(0, 5).Select(i => new DataHistoryReadItem("c" + i, View)).ToArray();
var wire = DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest(new DataHistoryRawDetails(null, null, 0, false), items, Budget));
Should.Throw<ArgumentException>(() => DataHistoryProtoMapper.DecodeRequest(wire, new DataDecodeLimits(MaxItems: 4)));
var processed = DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest(
new DataHistoryProcessedDetails(null, null, TimeSpan.FromSeconds(1), null), items, Budget));
processed.Processed.Aggregate.RemoveAt(0);
Should.Throw<ArgumentException>(() => DataHistoryProtoMapper.DecodeRequest(processed), "aggregates must be parallel to items");
Should.Throw<ArgumentException>(() => DataHistoryProtoMapper.DecodeRequest(new W.HistoryReadRequest { Budget = DataProtoMapper.EncodeBudget(Budget) }),
"details are required");
}
private static DataHistorySample Sample(uint status, DateTimeOffset? source, DateTimeOffset? server) =>
new(DataValue.FromScalar(DataValueKind.Int32, 7), status, source, server);
private static DateTimeOffset At(int seconds) => new DateTimeOffset(2026, 11, 23, 0, 0, 0, TimeSpan.Zero).AddSeconds(seconds);
private static DataHistoryReadResult RoundTrip(DataHistoryReadResult result) =>
DataHistoryProtoMapper.DecodeResult(W.HistoryReadResult.Parser.ParseFrom(DataHistoryProtoMapper.EncodeResult(result).ToByteArray()));
private static DataHistoryReadRequest Decode(DataHistoryReadRequest request) =>
DataHistoryProtoMapper.DecodeRequest(W.HistoryReadRequest.Parser.ParseFrom(DataHistoryProtoMapper.EncodeRequest(request).ToByteArray())).Request;
}