diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataHistoryProtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataHistoryProtoMapper.cs new file mode 100644 index 000000000..a2a869b99 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataHistoryProtoMapper.cs @@ -0,0 +1,247 @@ +using Google.Protobuf; +using Google.Protobuf.WellKnownTypes; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Commons.DataConnections; + +/// +/// H2 remote-history codecs (plan §4.2, §3.3). Fidelity rules: the full uint32 status (info bits included) passes +/// through unchanged; timestamps travel as protobuf Timestamp (100 ns domain precision, finer is refused); an +/// ABSENT start/end/sample timestamp stays absent — never ; the aggregate +/// configuration is carried verbatim (the origin decides whether it is servable); a value whose kind disagrees with +/// the catalog is BadTypeMismatch with a null value, never coerced. +/// +public static class DataHistoryProtoMapper +{ + /// OPC UA Bad_TypeMismatch. + public const uint BadTypeMismatch = 0x80740000u; + + /// Encodes a request (the release flag set ⇒ continuations only, no details needed but still sent). + public static W.HistoryReadRequest EncodeRequest(DataHistoryReadRequest request, bool releaseContinuations = false) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(request.Items); + var wire = new W.HistoryReadRequest { Budget = DataProtoMapper.EncodeBudget(request.Budget), ReleaseContinuations = releaseContinuations }; + foreach (var item in request.Items) + { + ArgumentNullException.ThrowIfNull(item); + var encoded = new W.HistoryReadItem { CorrelationId = item.CorrelationId ?? "", View = DataProtoMapper.EncodeView(item.View) }; + if (item.Continuation is { } token) encoded.Continuation = ByteString.CopyFrom(token); + wire.Items.Add(encoded); + } + switch (request.Details) + { + case DataHistoryRawDetails raw: + var r = new W.RawDetails { NumValuesPerNode = raw.NumValuesPerNode, ReturnBounds = raw.ReturnBounds }; + if (raw.StartUtc is { } rs) r.Start = Timestamp.FromDateTimeOffset(rs); + if (raw.EndUtc is { } re) r.End = Timestamp.FromDateTimeOffset(re); + wire.Raw = r; + break; + case DataHistoryProcessedDetails processed: + var p = new W.ProcessedDetails { IntervalTicks = processed.ProcessingInterval.Ticks }; + if (processed.StartUtc is { } ps) p.Start = Timestamp.FromDateTimeOffset(ps); + if (processed.EndUtc is { } pe) p.End = Timestamp.FromDateTimeOffset(pe); + foreach (var item in request.Items) + p.Aggregate.Add(item.AggregateId is { } id ? DataHistoryAggregates.NameOf(id) : ""); + if (processed.Configuration is { } c) + p.Configuration = new W.AggregateConfiguration + { + UseServerCapabilitiesDefaults = c.UseServerCapabilitiesDefaults, TreatUncertainAsBad = c.TreatUncertainAsBad, + PercentDataBad = c.PercentDataBad, PercentDataGood = c.PercentDataGood, UseSlopedExtrapolation = c.UseSlopedExtrapolation, + }; + wire.Processed = p; + break; + case DataHistoryAtTimeDetails atTime: + var a = new W.AtTimeDetails { UseSimpleBounds = atTime.UseSimpleBounds }; + a.Times.AddRange(atTime.RequestedTimesUtc.Select(Timestamp.FromDateTimeOffset)); + wire.AtTime = a; + break; + default: + throw new ArgumentException("Unsupported history details.", nameof(request)); + } + return wire; + } + + /// Decodes a request under the receiver's limits; malformed or oversized input is an . + public static (DataHistoryReadRequest Request, bool ReleaseContinuations) DecodeRequest(W.HistoryReadRequest wire, DataDecodeLimits? limits = null) + { + ArgumentNullException.ThrowIfNull(wire); + limits ??= new DataDecodeLimits(); + limits.Validate(); + if (wire.Items.Count > limits.MaxItems || wire.CalculateSize() > limits.MaxBytes) + throw new ArgumentException("Envelope exceeds receiver limits."); + var budget = DataProtoMapper.DecodeBudget(wire.Budget ?? throw new ArgumentException("Missing budget.")); + DataHistoryDetails details; + IReadOnlyList? aggregates = null; + switch (wire.DetailsCase) + { + case W.HistoryReadRequest.DetailsOneofCase.Raw: + details = new DataHistoryRawDetails(Optional(wire.Raw.Start), Optional(wire.Raw.End), wire.Raw.NumValuesPerNode, wire.Raw.ReturnBounds); + break; + case W.HistoryReadRequest.DetailsOneofCase.Processed: + var p = wire.Processed; + if (p.IntervalTicks < 0) throw new ArgumentException("Negative processing interval."); + if (p.Aggregate.Count != wire.Items.Count) throw new ArgumentException("Aggregates must be parallel to items."); + DataAggregateConfiguration? configuration = null; + if (p.Configuration is { } c) + { + if (c.PercentDataBad > byte.MaxValue || c.PercentDataGood > byte.MaxValue) + throw new ArgumentException("Aggregate configuration percentage out of range."); + configuration = new(c.UseServerCapabilitiesDefaults, c.TreatUncertainAsBad, (byte)c.PercentDataBad, + (byte)c.PercentDataGood, c.UseSlopedExtrapolation); + } + details = new DataHistoryProcessedDetails(Optional(p.Start), Optional(p.End), TimeSpan.FromTicks(p.IntervalTicks), configuration); + aggregates = p.Aggregate; + break; + case W.HistoryReadRequest.DetailsOneofCase.AtTime: + if (wire.AtTime.Times.Count > limits.MaxValueElements) throw new ArgumentException("Too many requested times."); + details = new DataHistoryAtTimeDetails(wire.AtTime.Times.Select(TypedValueCodec.DecodeTimestamp).ToArray(), wire.AtTime.UseSimpleBounds); + break; + default: + throw new ArgumentException("Missing history details."); + } + var items = new DataHistoryReadItem[wire.Items.Count]; + for (var i = 0; i < items.Length; i++) + { + var item = wire.Items[i]; + var view = DataProtoMapper.DecodeView(item.View ?? throw new ArgumentException("Missing view.")); + if (item.HasContinuation && item.Continuation.Length > 4096) throw new ArgumentException("Continuation too large."); + items[i] = new DataHistoryReadItem(item.CorrelationId, view, + aggregates is null ? null : DataHistoryAggregates.IdOf(aggregates[i]) ?? UnknownAggregate, + item.HasContinuation ? item.Continuation.ToByteArray() : null); + } + return (new DataHistoryReadRequest(details, items, budget), wire.ReleaseContinuations); + } + + /// + /// The id a decoded aggregate name this build cannot name maps to: ns=0 id 0 is no AggregateFunction, so the origin + /// answers BadAggregateNotSupported — the same as an aggregate it does not serve. + /// + public const uint UnknownAggregate = 0; + + /// Encodes one result. (the node's declared kind, or null) triggers the BadTypeMismatch rule. + public static W.HistoryReadResult EncodeResult(DataHistoryReadResult result, DataMetadata? catalog = null) + { + ArgumentNullException.ThrowIfNull(result); + var wire = new W.HistoryReadResult { CorrelationId = result.CorrelationId ?? "", StatusCode = result.StatusCode, ChunkContinues = result.ChunkContinues }; + foreach (var sample in result.Samples) wire.Samples.Add(EncodeSample(sample, catalog)); + if (result.Continuation is { } token) wire.Continuation = ByteString.CopyFrom(token); + if (result.Diagnostic is not null) wire.Diagnostic = result.Diagnostic; + if (result.ChunkContinues && result.Continuation is null) throw new ArgumentException("A continuing chunk needs its token."); + return wire; + } + + /// Encodes a sample; a value whose kind disagrees with becomes null + . + public static W.HistorySample EncodeSample(DataHistorySample sample, DataMetadata? catalog = null) + { + ArgumentNullException.ThrowIfNull(sample); + var mismatch = catalog is not null && !KindMatches(catalog, sample.Value); + var wire = new W.HistorySample { StatusCode = mismatch ? BadTypeMismatch : sample.StatusCode }; + if (mismatch) + { + using var none = DataValue.Null(); + wire.Value = TypedValueCodec.Encode(none); + } + else wire.Value = TypedValueCodec.Encode(sample.Value); + if (sample.SourceTimestampUtc is { } source) wire.SourceTimestamp = new W.TimestampOverride { Value = Timestamp.FromDateTimeOffset(source) }; + if (sample.ServerTimestampUtc is { } server) wire.ServerTimestamp = new W.TimestampOverride { Value = Timestamp.FromDateTimeOffset(server) }; + return wire; + } + + /// Decodes one result; (the catalog metadata, when known) applies the BadTypeMismatch rule again. + public static DataHistoryReadResult DecodeResult(W.HistoryReadResult wire, DataDecodeLimits? limits = null, DataMetadata? expected = null) + { + ArgumentNullException.ThrowIfNull(wire); + limits ??= new DataDecodeLimits(); + limits.Validate(); + if (wire.Samples.Count > limits.MaxValueElements) throw new ArgumentException("Too many history samples."); + if (wire.ChunkContinues && !wire.HasContinuation) throw new ArgumentException("A continuing chunk needs its token."); + var samples = new List(wire.Samples.Count); + try + { + foreach (var sample in wire.Samples) samples.Add(DecodeSample(sample, limits, expected)); + return new DataHistoryReadResult(wire.CorrelationId, wire.StatusCode, samples, + wire.HasContinuation ? wire.Continuation.ToByteArray() : null, wire.HasDiagnostic ? wire.Diagnostic : null, wire.ChunkContinues); + } + catch + { + foreach (var sample in samples) sample.Dispose(); + throw; + } + } + + /// Decodes one sample: absent timestamps stay absent; a kind mismatch against is BadTypeMismatch. + public static DataHistorySample DecodeSample(W.HistorySample wire, DataDecodeLimits? limits = null, DataMetadata? expected = null) + { + ArgumentNullException.ThrowIfNull(wire); + limits ??= new DataDecodeLimits(); + var source = wire.SourceTimestamp is { Value: { } s } ? TypedValueCodec.DecodeTimestamp(s) : (DateTimeOffset?)null; + var server = wire.ServerTimestamp is { Value: { } t } ? TypedValueCodec.DecodeTimestamp(t) : (DateTimeOffset?)null; + var value = TypedValueCodec.Decode(wire.Value ?? throw new ArgumentException("Missing history value."), limits.MaxValueElements, limits.MaxBytes); + if (expected is not null && !KindMatches(expected, value)) + { + value.Dispose(); + return new DataHistorySample(DataValue.Null(), BadTypeMismatch, source, server); + } + return new DataHistorySample(value, wire.StatusCode, source, server); + } + + /// Encodes a response. + public static W.HistoryReadResponse EncodeResponse(IReadOnlyList results, Func? catalog = null) + { + ArgumentNullException.ThrowIfNull(results); + var response = new W.HistoryReadResponse(); + for (var i = 0; i < results.Count; i++) response.Items.Add(EncodeResult(results[i], catalog?.Invoke(i))); + return response; + } + + /// Decodes a response's items. + public static IReadOnlyList DecodeResponse(W.HistoryReadResponse wire, DataDecodeLimits? limits = null) + { + ArgumentNullException.ThrowIfNull(wire); + limits ??= new DataDecodeLimits(); + if (wire.Items.Count > limits.MaxItems || wire.CalculateSize() > limits.MaxBytes) throw new ArgumentException("Envelope exceeds receiver limits."); + var results = new List(wire.Items.Count); + try + { + foreach (var item in wire.Items) results.Add(DecodeResult(item, limits)); + return results; + } + catch + { + foreach (var result in results) result.Dispose(); + throw; + } + } + + /// Encodes history capabilities. + public static W.HistoryCapabilities EncodeCapabilities(DataHistoryCapabilities x) + { + x.Validate(); + var wire = new W.HistoryCapabilities + { + Raw = x.Raw, Processed = x.Processed, AtTime = x.AtTime, TimestampResolutionTicks = x.TimestampResolutionTicks, + MaxValuesPerPage = x.MaxValuesPerPage, MaxConcurrentReads = x.MaxConcurrentReads, ContinuationIdleTicks = x.ContinuationIdle.Ticks, + }; + wire.Aggregates.AddRange(x.Aggregates); + return wire; + } + + /// Decodes history capabilities; an invalid advertisement is ignored (null = the feature is not available), never fatal. + public static DataHistoryCapabilities? DecodeCapabilities(W.HistoryCapabilities? wire) + { + if (wire is null || wire.Aggregates.Count > 256) return null; + var result = new DataHistoryCapabilities(wire.Raw, wire.Processed, wire.AtTime, wire.Aggregates.ToArray(), + wire.TimestampResolutionTicks, wire.MaxValuesPerPage, wire.MaxConcurrentReads, TimeSpan.FromTicks(wire.ContinuationIdleTicks)); + try { result.Validate(); return result; } + catch (ArgumentException) { return null; } + } + + private static DateTimeOffset? Optional(Timestamp? value) => value is null ? null : TypedValueCodec.DecodeTimestamp(value); + + /// The catalog rule: a null value always matches; otherwise the kind (and array element kind) must equal the declared one. + public static bool KindMatches(DataMetadata metadata, DataValue value) => + value.Kind == DataValueKind.Null || metadata.ValueKind == value.Kind + && (value.Kind != DataValueKind.Array || metadata.ArrayElementKind == value.ArrayElementKind); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs index b75f0d9c7..6c1fa1781 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs @@ -262,6 +262,9 @@ public static class DataProtoMapper v.StableSourceId = x.StableSourceId; if (x.EngineeringUnits is not null) v.EngineeringUnits = x.EngineeringUnits; + // H2: the service strips this (and the HistoryRead bit) from every response of a call that did not negotiate history. + if (x.History is { } history) + v.History = new W.HistoryInfo { Historizing = history.Historizing }; return v; } @@ -287,7 +290,9 @@ public static class DataProtoMapper x.HasStableSourceId ? x.StableSourceId : null, x.HasEngineeringUnits ? x.EngineeringUnits : null, x.IsStale, - x.HasArrayElementKind ? (DataValueKind)x.ArrayElementKind : null + x.HasArrayElementKind ? (DataValueKind)x.ArrayElementKind : null, + null, + x.History is { } history ? new DataHistoryInfo(history.Historizing) : null ); metadata.Validate(); return metadata; @@ -1029,6 +1034,9 @@ public static class DataProtoMapper }, }; v.ValueKinds.AddRange(x.ValueKinds.Select(k => (W.ValueKind)k)); + // H2: the service strips this from a call that did not negotiate history. + if (x.History is { } history) + v.History = DataHistoryProtoMapper.EncodeCapabilities(history); return v; } @@ -1073,7 +1081,8 @@ public static class DataProtoMapper x.ResponseServingIdentity, x.WriteServingGenerationEnforced, x.SubscriptionFreshnessChallenges, - x.MetadataItemLeases + x.MetadataItemLeases, + DataHistoryProtoMapper.DecodeCapabilities(x.History) ); result.Validate(); return result; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs index 644d5eba8..c0a0b4e4d 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs @@ -19,12 +19,12 @@ public static class DataConnectionProtoContract public const int MaxFeaturesHeaderLength = 256; // X0 field reservations (history + alarm plan §4.2). Not protobuf `reserved`: each number is held for the - // named field of a later phase. GrpcDataProtoReservationTests pins each as unused-or-that-field. - /// CapabilitiesResponse.history (H2). + // named field of a later phase. GrpcDataProtoReservationTests pins each as unused-or-that-field; H2 took 16 and 14. + /// CapabilitiesResponse.history (H2, in use). public const int CapabilitiesHistoryField = 16; /// CapabilitiesResponse.conditions (A2). public const int CapabilitiesConditionsField = 17; - /// Metadata.history (H2). + /// Metadata.history (H2, in use). public const int MetadataHistoryField = 14; /// SubscriptionItem.condition_scope (A2). public const int SubscriptionItemConditionScopeField = 4; @@ -37,6 +37,10 @@ public static class DataConnectionProtoContract TypedValue.KindFieldNumber != 1 || Sample.StatusCodeFieldNumber != 2 || SubscriptionFrame.CompactValuesFieldNumber != 7 + || CapabilitiesResponse.HistoryFieldNumber != CapabilitiesHistoryField + || Metadata.HistoryFieldNumber != MetadataHistoryField + || HistoryReadRequest.ReleaseContinuationsFieldNumber != 6 + || HistoryReadResult.ChunkContinuesFieldNumber != 6 || (int)ValueKind.Unspecified != 0 || !Reserved(CapabilitiesResponse.Descriptor, CapabilitiesHistoryField, "history", "HistoryCapabilities") || !Reserved(CapabilitiesResponse.Descriptor, CapabilitiesConditionsField, "conditions", "ConditionCapabilities") diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto index d048729e8..28a230c64 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto @@ -9,6 +9,8 @@ service DataConnectionService { rpc Read(ReadRequest) returns (ReadResponse); rpc Write(WriteRequest) returns (WriteResponse); rpc Subscribe(stream SubscriptionCommand) returns (stream SubscriptionFrame); + // H2: header-gated (x-otopcua-data-features: history). Without the negotiated feature ⇒ FAILED_PRECONDITION. + rpc HistoryRead(HistoryReadRequest) returns (HistoryReadResponse); } enum ValueKind { VALUE_KIND_UNSPECIFIED = 0; @@ -119,8 +121,24 @@ message CapabilitiesResponse { bool subscription_freshness_challenges = 14; // Good GetMetadata results may include an exact-item authority lease. bool metadata_item_leases = 15; - // X0 RESERVATION (not protobuf `reserved`: the numbers WILL be used): 16 = HistoryCapabilities history (H2), - // 17 = ConditionCapabilities conditions (A2). Pinned by DataConnectionProtoContract + GrpcDataProtoReservationTests. + // H2: only on a call that negotiated `history`, and only when this origin has a historian backend. + HistoryCapabilities history = 16; + // X0 RESERVATION (not protobuf `reserved`: the number WILL be used): 17 = ConditionCapabilities conditions (A2). + // Pinned by DataConnectionProtoContract + GrpcDataProtoReservationTests. +} +message HistoryCapabilities { + bool raw = 1; + bool processed = 2; + bool at_time = 3; + // Stable HistoryAggregateType names the origin's backend serves. + repeated string aggregates = 4; + int64 timestamp_resolution_ticks = 5; + int32 max_values_per_page = 6; + int32 max_concurrent_reads = 7; + int64 continuation_idle_ticks = 8; +} +message HistoryInfo { + bool historizing = 1; } message Metadata { View view = 1; @@ -136,7 +154,8 @@ message Metadata { optional string engineering_units = 11; bool is_stale = 12; optional ValueKind array_element_kind = 13; - // X0 RESERVATION: 14 = HistoryInfo history (H2). Pinned by GrpcDataProtoReservationTests. + // H2: only on a call that negotiated `history`. + HistoryInfo history = 14; } message Lease { int64 catalog_epoch = 1; @@ -325,3 +344,67 @@ message SubscriptionFrame { // negotiated `conditions` through x-otopcua-data-features: v1 clients fault on an unknown frame arm. } } +// H2 remote history (plan §4.2). An unset start/end is ABSENT, never MinValue: the origin's end-only rules depend on it. +message HistoryReadItem { + string correlation_id = 1; + View view = 2; + // A page continuation or a transport chunk token from a previous response; absent = a fresh read. + optional bytes continuation = 3; +} +message HistoryReadRequest { + repeated HistoryReadItem items = 1; + Budget budget = 2; + oneof details { + RawDetails raw = 3; + ProcessedDetails processed = 4; + AtTimeDetails at_time = 5; + } + // The only release mechanism (m2): drop the items' continuations without reading. + bool release_continuations = 6; +} +message RawDetails { + optional google.protobuf.Timestamp start = 1; + optional google.protobuf.Timestamp end = 2; + uint32 num_values_per_node = 3; + bool return_bounds = 4; +} +message AggregateConfiguration { + bool use_server_capabilities_defaults = 1; + bool treat_uncertain_as_bad = 2; + uint32 percent_data_bad = 3; + uint32 percent_data_good = 4; + bool use_sloped_extrapolation = 5; +} +message ProcessedDetails { + optional google.protobuf.Timestamp start = 1; + optional google.protobuf.Timestamp end = 2; + int64 interval_ticks = 3; + // Parallel to items: stable HistoryAggregateType names. + repeated string aggregate = 4; + // Client values verbatim; absent = server defaults. The origin's IsServable decides (m8). + AggregateConfiguration configuration = 5; +} +message AtTimeDetails { + repeated google.protobuf.Timestamp times = 1; + bool use_simple_bounds = 2; +} +message HistorySample { + TypedValue value = 1; + // The full OPC UA status, info bits included. + uint32 status_code = 2; + TimestampOverride source_timestamp = 3; + TimestampOverride server_timestamp = 4; +} +message HistoryReadResult { + string correlation_id = 1; + uint32 status_code = 2; + repeated HistorySample samples = 3; + optional bytes continuation = 4; + optional string diagnostic = 5; + // This is one bounded chunk; resume with `continuation` under the same details for the rest. + bool chunk_continues = 6; +} +message HistoryReadResponse { + repeated HistoryReadResult items = 1; + Serving serving = 2; +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs index 7a6ef751c..bd301cb88 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs @@ -228,14 +228,14 @@ public sealed record DataBudget(TimeSpan Timeout, int MaxItems, long MaxBytes) } /// /// Data operation grants. The values are persisted (ConfigDb int) and carried on the wire (uint); never renumber. -/// Bits 32..512 are RESERVED by phase X0 of the history/alarm plan: no node implements them yet, so every reader -/// masks them to (an unknown grant is no grant) and the authoring -/// validator keeps rejecting them until the phase that implements each one (H2, A2). +/// Bits 32..512 were RESERVED by phase X0 of the history/alarm plan. Every reader masks to +/// (an unknown grant is no grant) and the authoring validator rejects a bit +/// until the phase that implements it: H2 implements ; A2 the alarm bits. /// [Flags] public enum DataOperations { None = 0, Browse = 1, Metadata = 2, Read = 4, Write = 8, Subscribe = 16, - /// Reserved (H2): Raw/Processed/AtTime history reads. + /// H2: Raw/Processed/AtTime history reads. HistoryRead = 32, /// Reserved (A2): root-scoped condition items (origin-side grant). AlarmSubscribe = 64, @@ -254,11 +254,11 @@ public static class DataOperationSets DataOperations.Write | DataOperations.Subscribe; /// /// What tolerant readers keep; every other bit is dropped fail-closed. Grows only in the phase that implements - /// a bit (H2 adds ; A2 the alarm bits). + /// a bit (H2 added ; A2 adds the alarm bits). /// - public const DataOperations Understood = V1; - /// Bits reserved by X0 for later phases. - public const DataOperations Reserved = DataOperations.HistoryRead | DataOperations.AlarmSubscribe | + public const DataOperations Understood = V1 | DataOperations.HistoryRead; + /// Bits reserved by X0 that no phase has implemented yet (H2 took out). + public const DataOperations Reserved = DataOperations.AlarmSubscribe | DataOperations.AlarmAcknowledge | DataOperations.AlarmConfirm | DataOperations.AlarmShelve; } /// @@ -283,11 +283,39 @@ public sealed record DataLimits(int MaxPageItems, int MaxBatchItems, int MaxMess } } } +/// +/// Remote history an origin can serve (plan §4.2, CapabilitiesResponse.history). Advertised only when the origin +/// has a historian backend AND the call negotiated ; null otherwise. +/// +/// HistoryRead-Raw. +/// HistoryRead-Processed (at least one aggregate served). +/// HistoryRead-AtTime. +/// The served aggregates, as stable HistoryAggregateType names. +/// The backend's stored timestamp resolution (QuestDB µs = 10); 1 = 100 ns. +/// The origin's per-node page ceiling for this caller. +/// The origin's concurrent history reads admitted per principal. +/// How long an untaken origin continuation lives. +public sealed record DataHistoryCapabilities(bool Raw, bool Processed, bool AtTime, IReadOnlyList Aggregates, + long TimestampResolutionTicks, int MaxValuesPerPage, int MaxConcurrentReads, TimeSpan ContinuationIdle) +{ + public void Validate() + { + ArgumentNullException.ThrowIfNull(Aggregates); + if (TimestampResolutionTicks <= 0 || MaxValuesPerPage <= 0 || MaxConcurrentReads <= 0 || ContinuationIdle <= TimeSpan.Zero + || Aggregates.Any(string.IsNullOrWhiteSpace)) + throw new ArgumentOutOfRangeException(nameof(MaxValuesPerPage), "History capabilities must be positive."); + } +} + +/// Per-node history metadata (Metadata.history); only on a call that negotiated history. +/// The caller may HistoryRead this node (historized AND granted — never one without the other). +public sealed record DataHistoryInfo(bool Historizing); + public sealed record DataCapabilities(int ProtocolMajor, int ProtocolMinor, ServingIdentity Serving, DataReadiness Readiness, DataOperations Operations, IReadOnlySet ValueKinds, DataLimits Limits, bool CompactBatches, int CompactCodecVersion, string ClusterId, bool SubscriptionAgeReadiness = false, bool ResponseServingIdentity = false, bool WriteServingGenerationEnforced = false, bool SubscriptionFreshnessChallenges = false, - bool MetadataItemLeases = false) + bool MetadataItemLeases = false, DataHistoryCapabilities? History = null) { private readonly DataOperations _operations = Operations & DataOperationSets.Understood; /// Masked to on construction and on every with. @@ -312,11 +340,13 @@ public sealed record DataCapabilities(int ProtocolMajor, int ProtocolMinor, Serv DataContractValidation.Required(kind); } // Operations is masked by its accessor, so unknown bits from a newer peer never reach here (X0). + History?.Validate(); } } public sealed record DataMetadata(DataView View, string BrowseName, string NodeKind, DataValueKind ValueKind, int ValueRank, IReadOnlyList Dimensions, bool Writable, DataOperations AllowedOperations, long CatalogRevision, - string? StableSourceId, string? EngineeringUnits, bool IsStale, DataValueKind? ArrayElementKind = null, ServingIdentity? Serving = null) + string? StableSourceId, string? EngineeringUnits, bool IsStale, DataValueKind? ArrayElementKind = null, ServingIdentity? Serving = null, + DataHistoryInfo? History = null) { public void Validate() { diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataHistoryAggregates.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataHistoryAggregates.cs new file mode 100644 index 000000000..00bae5d85 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataHistoryAggregates.cs @@ -0,0 +1,58 @@ +using System.Collections.Frozen; + +namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +/// +/// The wire names of the standard Part 13 aggregates a remote HistoryRead-Processed can carry (plan §4.2: "stable +/// HistoryAggregateType names"), and their ns=0 numeric AggregateFunction NodeIds. SDK-free; pinned against the SDK's +/// ObjectIds.AggregateFunction_* by the OpcUaServer tests (GrpcDataHistoryAggregateTableTests). +/// +public static class DataHistoryAggregates +{ + /// Wire name ⇒ ns=0 AggregateFunction id. + public static readonly FrozenDictionary IdByName = new Dictionary(StringComparer.Ordinal) + { + [nameof(HistoryAggregateType.Average)] = 2342, + [nameof(HistoryAggregateType.Minimum)] = 2346, + [nameof(HistoryAggregateType.Maximum)] = 2347, + [nameof(HistoryAggregateType.Total)] = 2344, + [nameof(HistoryAggregateType.Count)] = 2352, + [nameof(HistoryAggregateType.Interpolative)] = 2341, + [nameof(HistoryAggregateType.TimeAverage)] = 2343, + [nameof(HistoryAggregateType.Start)] = 2357, + [nameof(HistoryAggregateType.End)] = 2358, + [nameof(HistoryAggregateType.Delta)] = 2359, + [nameof(HistoryAggregateType.Range)] = 2350, + [nameof(HistoryAggregateType.MinimumActualTime)] = 2348, + [nameof(HistoryAggregateType.MaximumActualTime)] = 2349, + [nameof(HistoryAggregateType.StartBound)] = 11505, + [nameof(HistoryAggregateType.EndBound)] = 11506, + [nameof(HistoryAggregateType.DeltaBounds)] = 11507, + [nameof(HistoryAggregateType.DurationGood)] = 2360, + [nameof(HistoryAggregateType.DurationBad)] = 2361, + [nameof(HistoryAggregateType.PercentGood)] = 2362, + [nameof(HistoryAggregateType.PercentBad)] = 2363, + [nameof(HistoryAggregateType.WorstQuality)] = 2364, + [nameof(HistoryAggregateType.NumberOfTransitions)] = 2355, + [nameof(HistoryAggregateType.AnnotationCount)] = 2351, + [nameof(HistoryAggregateType.StandardDeviationPopulation)] = 11427, + [nameof(HistoryAggregateType.VariancePopulation)] = 11429, + [nameof(HistoryAggregateType.TimeAverage2)] = 11285, + [nameof(HistoryAggregateType.Total2)] = 11304, + }.ToFrozenDictionary(StringComparer.Ordinal); + + /// ns=0 AggregateFunction id ⇒ wire name. + public static readonly FrozenDictionary NameById = IdByName.ToFrozenDictionary(x => x.Value, x => x.Key); + + /// The wire name of an aggregate id; an id outside the table travels as i=<id> (the origin refuses it). + /// The ns=0 numeric id. + /// The wire name. + public static string NameOf(uint aggregateId) => + NameById.TryGetValue(aggregateId, out var name) ? name + : "i=" + aggregateId.ToString(System.Globalization.CultureInfo.InvariantCulture); + + /// The ns=0 id behind a wire name; null for a name this build cannot name (the origin answers BadAggregateNotSupported). + /// The wire name. + /// The id, or null. + public static uint? IdOf(string? name) => name is not null && IdByName.TryGetValue(name, out var id) ? id : null; +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs index ebaf564a4..575b0ecc3 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs @@ -220,7 +220,8 @@ public sealed record DataHistoryProcessedDetails( /// Part 11 ReadAtTimeDetails. /// The requested times, in order. -public sealed record DataHistoryAtTimeDetails(IReadOnlyList RequestedTimesUtc) : DataHistoryDetails; +/// Part 11 useSimpleBounds, carried verbatim (the origin's AtTime evaluator applies its own rules). +public sealed record DataHistoryAtTimeDetails(IReadOnlyList RequestedTimesUtc, bool UseSimpleBounds = false) : DataHistoryDetails; /// One node of a remote history read. /// Echoed on the result. @@ -247,7 +248,18 @@ public sealed record DataHistorySample(DataValue Value, uint StatusCode, DateTim /// BadAggregateNotSupported, GoodNoData …), its samples and the origin's next continuation token (null /// when the read is complete). Owns its samples. /// -public sealed record DataHistoryReadResult(string CorrelationId, uint StatusCode, IReadOnlyList Samples, byte[]? Continuation) +/// The request item's correlation id. +/// The full OPC UA operation status. +/// The returned values (owned). +/// The next token (a page continuation, or a transport chunk token when ). +/// Optional non-sensitive diagnostic text. +/// +/// Transport only (H2): this result is one bounded chunk of a larger answer; resume with +/// under the same details to get the rest. A caller-facing never returns it set — +/// the gRPC client assembles the chunks. +/// +public sealed record DataHistoryReadResult(string CorrelationId, uint StatusCode, IReadOnlyList Samples, byte[]? Continuation, + string? Diagnostic = null, bool ChunkContinues = false) : IDisposable { public void Dispose() @@ -269,3 +281,27 @@ public interface IDataHistoryService /// Releases continuation tokens without reading (Part 11 releaseContinuationPoints); best effort, idempotent. Task ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken); } + +/// +/// The transport channel a peer history read arrives on (H2). Origin continuations live in one store per +/// (authenticated principal, channel): a peer never reaches another channel's cursors, and the store is cleared when +/// fires (the HTTP/2 connection ended). A direct runtime consumer's channel is its facade. +/// +/// A stable, non-secret id of the transport connection. +/// Fires when the transport connection closes; = idle expiry only. +public sealed record DataHistoryChannel(string ChannelId, CancellationToken Closed); + +/// +/// The origin-side history entry a TRANSPORT uses (H2): like , but bound to the +/// transport channel and allowed to split an answer into bounded chunks () +/// under the export's response-byte cap. Implemented by the origin's caller-bound facade. +/// +public interface IDataHistoryTransport +{ + /// Reads for a transport response; results in request order, possibly chunked. + Task> ReadForTransportAsync(DataHistoryReadRequest request, DataHistoryChannel channel, + CancellationToken cancellationToken); + + /// Releases page or chunk tokens of ; best effort, idempotent. + Task ReleaseForTransportAsync(IReadOnlyList continuations, DataHistoryChannel channel, CancellationToken cancellationToken); +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataFeatureHeaderTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataFeatureHeaderTests.cs index f854f542b..0bdb54816 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataFeatureHeaderTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataFeatureHeaderTests.cs @@ -74,7 +74,8 @@ public sealed class GrpcDataTolerantDecodeTests { var wire = DataProtoMapper.EncodeMetadata(new DataMetadata(View, "x", "Variable", DataValueKind.Int32, -1, [], true, DataOperations.Read | DataOperations.Subscribe, 1, null, null, false)); - wire.AllowedOperations |= 32u | 64u | 128u | 256u | 512u | (1u << 20) | 0x8000_0000u; + // 32 (HistoryRead) is understood since H2; the still-reserved and unknown bits are dropped. + wire.AllowedOperations |= 64u | 128u | 256u | 512u | (1u << 20) | 0x8000_0000u; var decoded = DataProtoMapper.DecodeMetadata(wire); decoded.AllowedOperations.ShouldBe(DataOperations.Read | DataOperations.Subscribe); } @@ -86,7 +87,7 @@ public sealed class GrpcDataTolerantDecodeTests DataOperations.Browse | DataOperations.Write, new HashSet { DataValueKind.Int32 }, new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)), false, 0, "c"); var wire = DataProtoMapper.EncodeCapabilities(caps); - wire.Operations |= 32u | 512u | 0x8000_0000u; + wire.Operations |= 64u | 512u | 0x8000_0000u; DataProtoMapper.DecodeCapabilities(wire).Operations.ShouldBe(DataOperations.Browse | DataOperations.Write); } @@ -95,7 +96,7 @@ public sealed class GrpcDataTolerantDecodeTests { var response = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, new DataMetadata(View, "x", "Variable", DataValueKind.Int32, -1, [], false, DataOperations.Read, 1, null, null, false), null)]); - response.Items[0].Value.AllowedOperations |= 32u; + response.Items[0].Value.AllowedOperations |= 64u; var decoded = DataProtoMapper.DecodeMetadataResponse(response, new(16, 65536, 1000)); decoded.ShouldHaveSingleItem().Value!.AllowedOperations.ShouldBe(DataOperations.Read); W.Metadata.Descriptor.FindFieldByName("allowed_operations").FieldNumber.ShouldBe(8); diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataHistoryCodecTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataHistoryCodecTests.cs new file mode 100644 index 000000000..f378925ca --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataHistoryCodecTests.cs @@ -0,0 +1,212 @@ +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; + +/// H2 remote-history codecs (plan §4.2, §3.3 fidelity). +[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(() => 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(); + 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(); + 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= 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(); + 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(() => 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(() => 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(() => DataHistoryProtoMapper.DecodeRequest(processed), "aggregates must be parallel to items"); + Should.Throw(() => 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; +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataProtoContractTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataProtoContractTests.cs index 167a49c60..beaadf50e 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataProtoContractTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataProtoContractTests.cs @@ -17,7 +17,7 @@ public sealed class GrpcDataProtoContractTests methods .Select(m => m.Name) .ShouldBe( - new[] { "GetCapabilities", "Browse", "GetMetadata", "Read", "Write", "Subscribe" } + new[] { "GetCapabilities", "Browse", "GetMetadata", "Read", "Write", "Subscribe", "HistoryRead" } // H2 appended HistoryRead ); methods.Take(5).All(m => !m.IsClientStreaming && !m.IsServerStreaming).ShouldBeTrue(); var signatures = new[] diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataProtoReservationTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataProtoReservationTests.cs index 4f785b026..3e821b168 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataProtoReservationTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataProtoReservationTests.cs @@ -82,18 +82,16 @@ public sealed class GrpcDataProtoReservationTests if (arm is not null) arm.RealContainingOneof.ShouldNotBeNull().Name.ShouldBe("frame"); } - // X0-ONLY: the phase that adds one of these fields (H2: 16 and 14; A2: 17, 4 and 9) REPLACES this test with - // its own "advertised only when negotiated/provisioned" assertion. The reservation theory above stays. + // The X0 tripwire ("no field yet") was REPLACED by H2 for the numbers H2 took (16, 14 — pinned with their real types in + // GrpcDataHistoryCodecTests). The A2 numbers must still be unused; A2 replaces this in turn. [Fact] - public void X0_adds_no_field_yet_so_the_server_advertises_nothing_new() + public void Numbers_reserved_for_A2_are_still_unused() { foreach (var (descriptor, number) in new (MessageDescriptor, int)[] { - (CapabilitiesResponse.Descriptor, 16), (CapabilitiesResponse.Descriptor, 17), (Metadata.Descriptor, 14), - (SubscriptionItem.Descriptor, 4), (SubscriptionFrame.Descriptor, 9), + (CapabilitiesResponse.Descriptor, 17), (SubscriptionItem.Descriptor, 4), (SubscriptionFrame.Descriptor, 9), }) - descriptor.FindFieldByNumber(number).ShouldBeNull($"{descriptor.Name} field {number} must not exist before its phase"); - DataConnectionReflection.Descriptor.Services.Single().Methods.Count.ShouldBe(6); + descriptor.FindFieldByNumber(number).ShouldBeNull($"{descriptor.Name} field {number} must not exist before A2"); } [Fact] diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataOperationToleranceTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataOperationToleranceTests.cs index 7cbdeffe0..0ed7bec10 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataOperationToleranceTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataOperationToleranceTests.cs @@ -35,20 +35,21 @@ public sealed class GrpcDataOperationToleranceTests } [Fact] - public void X0_understands_only_v1_and_reserves_the_five_new_bits() + public void H2_understands_v1_plus_HistoryRead_and_still_reserves_the_four_alarm_bits() { DataOperationSets.V1.ShouldBe(DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe); - DataOperationSets.Understood.ShouldBe(DataOperationSets.V1); - DataOperationSets.Reserved.ShouldBe(DataOperations.HistoryRead | DataOperations.AlarmSubscribe | DataOperations.AlarmAcknowledge + // X0 understood V1 only; H2 grew it by HistoryRead (with the validator and Implemented(target)), A2 grows the rest. + DataOperationSets.Understood.ShouldBe(DataOperationSets.V1 | DataOperations.HistoryRead); + DataOperationSets.Reserved.ShouldBe(DataOperations.AlarmSubscribe | DataOperations.AlarmAcknowledge | DataOperations.AlarmConfirm | DataOperations.AlarmShelve); (DataOperationSets.Reserved & DataOperationSets.Understood).ShouldBe(DataOperations.None); - ((int)DataOperationSets.Reserved).ShouldBe(0x3E0); + ((int)DataOperationSets.Reserved).ShouldBe(0x3C0); } [Fact] public void Capabilities_mask_unknown_bits_on_construction_instead_of_throwing() { - var unknown = DataOperations.Read | DataOperations.HistoryRead | DataOperations.AlarmSubscribe | (DataOperations)(1 << 20); + var unknown = DataOperations.Read | DataOperations.AlarmShelve | DataOperations.AlarmSubscribe | (DataOperations)(1 << 20); var capabilities = Create(unknown); capabilities.Operations.ShouldBe(DataOperations.Read); Should.NotThrow(capabilities.Validate);