619b0c378d
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.
248 lines
14 KiB
C#
248 lines
14 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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 <c>Timestamp</c> (100 ns domain precision, finer is refused); an
|
|
/// ABSENT start/end/sample timestamp stays absent — never <see cref="DateTimeOffset.MinValue"/>; the aggregate
|
|
/// configuration is carried verbatim (the origin decides whether it is servable); a value whose kind disagrees with
|
|
/// the catalog is <c>BadTypeMismatch</c> with a null value, never coerced.
|
|
/// </summary>
|
|
public static class DataHistoryProtoMapper
|
|
{
|
|
/// <summary>OPC UA <c>Bad_TypeMismatch</c>.</summary>
|
|
public const uint BadTypeMismatch = 0x80740000u;
|
|
|
|
/// <summary>Encodes a request (the release flag set ⇒ continuations only, no details needed but still sent).</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>Decodes a request under the receiver's limits; malformed or oversized input is an <see cref="ArgumentException"/>.</summary>
|
|
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<string>? 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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The id a decoded aggregate name this build cannot name maps to: ns=0 id 0 is no AggregateFunction, so the origin
|
|
/// answers <c>BadAggregateNotSupported</c> — the same as an aggregate it does not serve.
|
|
/// </summary>
|
|
public const uint UnknownAggregate = 0;
|
|
|
|
/// <summary>Encodes one result. <paramref name="catalogKind"/> (the node's declared kind, or null) triggers the BadTypeMismatch rule.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>Encodes a sample; a value whose kind disagrees with <paramref name="catalog"/> becomes null + <see cref="BadTypeMismatch"/>.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>Decodes one result; <paramref name="expected"/> (the catalog metadata, when known) applies the BadTypeMismatch rule again.</summary>
|
|
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<DataHistorySample>(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;
|
|
}
|
|
}
|
|
|
|
/// <summary>Decodes one sample: absent timestamps stay absent; a kind mismatch against <paramref name="expected"/> is BadTypeMismatch.</summary>
|
|
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);
|
|
}
|
|
|
|
/// <summary>Encodes a response.</summary>
|
|
public static W.HistoryReadResponse EncodeResponse(IReadOnlyList<DataHistoryReadResult> results, Func<int, DataMetadata?>? 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;
|
|
}
|
|
|
|
/// <summary>Decodes a response's items.</summary>
|
|
public static IReadOnlyList<DataHistoryReadResult> 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<DataHistoryReadResult>(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;
|
|
}
|
|
}
|
|
|
|
/// <summary>Encodes history capabilities.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>Decodes history capabilities; an invalid advertisement is ignored (null = the feature is not available), never fatal.</summary>
|
|
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);
|
|
|
|
/// <summary>The catalog rule: a null value always matches; otherwise the kind (and array element kind) must equal the declared one.</summary>
|
|
public static bool KindMatches(DataMetadata metadata, DataValue value) =>
|
|
value.Kind == DataValueKind.Null || metadata.ValueKind == value.Kind
|
|
&& (value.Kind != DataValueKind.Array || metadata.ArrayElementKind == value.ArrayElementKind);
|
|
}
|