From b36c8d871645e3cf37ac0feee34173495fcaa5b4 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Mon, 23 Nov 2026 20:57:35 -0500 Subject: [PATCH] feat(grpc-data): H2 consumer history client and deployed-connection history GrpcDataConnection implements IDataHistoryService (explicitly; ReadHistoryAsync/ReleaseHistoryAsync avoid an overload clash with ReadAsync): the capabilities probe always asks for history, other calls send it only when the selected endpoint advertised it; per-call deadline min(remaining, HistoryTimeoutMilliseconds); FAILED_PRECONDITION/UNIMPLEMENTED => BadHistoryOperationUnsupported; chunks assembled within the request budget (BadTooManyOperations past it); page tokens wrapped with the issuing endpoint + serving incarnation so a resumed read never moves; release forwarded. The deployment lease gates history on the row's HistoryRead bit and carries HistoryTimeout. Decoded capabilities drop HistoryRead without the history field. X0 tests that used bit 32 as the unknown bit now use a still-reserved bit. --- .../DataConnections/DataProtoMapper.cs | 4 +- .../DataConnectionDeploymentRuntime.cs | 44 ++- .../GrpcDataConnection.History.cs | 287 ++++++++++++++++++ .../DataConnections/GrpcDataConnection.cs | 10 +- .../DataConnections/LocalDataConnection.cs | 8 +- .../GrpcDataArtifactReadTests.cs | 3 +- .../GrpcDataCatalogStagingTests.cs | 4 +- .../GrpcDataFeatureHeaderClientTests.cs | 13 +- .../GrpcDataHistoryClientTests.cs | 248 +++++++++++++++ .../GrpcDataUnknownOperationToleranceTests.cs | 24 +- 10 files changed, 614 insertions(+), 31 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs 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 6c1fa1781..6d15d85ef 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs @@ -1060,7 +1060,9 @@ public static class DataProtoMapper x.ProtocolMinor, DecodeServing(x.Serving), r, - (DataOperations)(x.Operations & (uint)DataOperationSets.Understood), + // H2: HistoryRead without the history capabilities field is no grant (the two only ever travel together). + (DataOperations)(x.Operations & (uint)DataOperationSets.Understood + & (DataHistoryProtoMapper.DecodeCapabilities(x.History) is null ? ~(uint)DataOperations.HistoryRead : uint.MaxValue)), kinds, new DataLimits( l.MaxPageItems, diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs index 7f712b127..d9c1ff8b1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -24,7 +24,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable { private sealed record Spec(string Id, long Revision, DataTarget Target, Uri[] Endpoints, HashSet EligibleNodes, string Secret, DataOperations Operations, TimeSpan Timeout, int Batch, int Page, int MessageBytes, - int Streams, int Monitored, long PendingBytes); + int Streams, int Monitored, long PendingBytes, TimeSpan HistoryTimeout = default); private sealed record Desired(long ScopeVersion, string ArtifactRevision, long Generation, RedundancyMode ConsumerMode, IReadOnlyDictionary Specs, IReadOnlyDictionary Allowlist); private sealed class Entry(Spec spec, long generation, GrpcDataConnection connection, CancellationToken token, @@ -192,7 +192,8 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable throw new ArgumentException("Cluster target has no eligible nodes.", nameof(snapshot)); var spec = new Spec(item.DataConnectionId, item.Revision, target, endpoints, eligible, item.SecretReference, operations, TimeSpan.FromMilliseconds(item.TimeoutMilliseconds), item.MaxBatchItems, - item.MaxPageItems, item.MaxMessageBytes, item.MaxStreams, item.MaxMonitoredItems, item.MaxPendingBytes); + item.MaxPageItems, item.MaxMessageBytes, item.MaxStreams, item.MaxMonitoredItems, item.MaxPendingBytes, + TimeSpan.FromMilliseconds(item.HistoryTimeoutMilliseconds > 0 ? item.HistoryTimeoutMilliseconds : 30000)); if (!specs.TryAdd(spec.Id, spec) || !allow.TryAdd(spec.Id, spec.Secret)) throw new ArgumentException("Duplicate connection identity.", nameof(snapshot)); } @@ -243,7 +244,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable a.Endpoints.SequenceEqual(b.Endpoints) && a.EligibleNodes.SetEquals(b.EligibleNodes) && string.Equals(a.Secret, b.Secret, StringComparison.Ordinal) && a.Operations == b.Operations && a.Timeout == b.Timeout && a.Batch == b.Batch && a.Page == b.Page && a.MessageBytes == b.MessageBytes && a.Streams == b.Streams && - a.Monitored == b.Monitored && a.PendingBytes == b.PendingBytes; + a.Monitored == b.Monitored && a.PendingBytes == b.PendingBytes && a.HistoryTimeout == b.HistoryTimeout; private bool MayAcquire() { try { return _consumerMayAcquire(); } catch (Exception) { return false; } } private DataConnectionConsumerRoleSnapshot? CaptureRole(RedundancyMode mode) { try { return _consumerRoleSnapshot?.Invoke(mode); } catch (Exception) { return null; } } @@ -428,7 +429,8 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable { var connection = new GrpcDataConnection(spec.Id, spec.Target, spec.Endpoints, _security, scope, spec.MessageBytes, spec.Endpoints.Length, _clock, spec.EligibleNodes, - spec.Streams, spec.Monitored, maxPendingCommandBytes: spec.PendingBytes, enableCompactBatches: _useCompactBatches); + spec.Streams, spec.Monitored, maxPendingCommandBytes: spec.PendingBytes, enableCompactBatches: _useCompactBatches) + { HistoryTimeout = spec.HistoryTimeout }; _entries.Add(spec.Id, new Entry(spec, desired.Generation, connection, scope.CancellationToken, desired.ConsumerMode, role) { Ready = true }); } catch (Exception) { scope.Dispose(); retryNeeded = true; } @@ -509,8 +511,40 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable } /// A non-owning handle with the deployed operation and resource policy. -public sealed class DataConnectionDeploymentLease : IDataConnection, IDisposable +public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IDisposable { + /// + /// H2 remote history through the deployed connection: needs the connection row's HistoryRead bit (masked to the + /// understood set) and an inner connection that implements history; otherwise every item is unsupported. + /// + public async Task> ReadHistoryAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + Check(DataOperations.HistoryRead); + if (request.Items.Count > _batch) throw new ArgumentOutOfRangeException(nameof(request)); + if (_inner is not IDataHistoryService history) + return request.Items.Select(x => new DataHistoryReadResult(x.CorrelationId, GrpcDataConnection.BadHistoryOperationUnsupported, [], null)).ToArray(); + // The deadline is the connection's HistoryTimeout (applied per call by GrpcDataConnection), not the unary timeout, + // and MaxBytes is the caller's chunk-assembly budget, so only the item count is clamped here. + request.Budget.Validate(); + var value = await history.ReadAsync(request with { Budget = request.Budget with { MaxItems = Math.Min(request.Budget.MaxItems, _batch) } }, + cancellationToken).ConfigureAwait(false); + try { Check(DataOperations.HistoryRead); return value; } + catch { foreach (var item in value) item.Dispose(); throw; } + } + + Task> IDataHistoryService.ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) => + ReadHistoryAsync(request, cancellationToken); + Task IDataHistoryService.ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) => + ReleaseHistoryAsync(continuations, cancellationToken); + + /// Releases continuations (best effort). + public Task ReleaseHistoryAsync(IReadOnlyList continuations, CancellationToken cancellationToken) + { + Check(DataOperations.HistoryRead); + return _inner is IDataHistoryService history ? history.ReleaseAsync(continuations, cancellationToken) : Task.CompletedTask; + } + private readonly IDataConnection _inner; private readonly CancellationToken _scope; private readonly DataOperations _allowed; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs new file mode 100644 index 000000000..f28b06800 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs @@ -0,0 +1,287 @@ +using System.Buffers.Binary; +using System.Text; +using Google.Protobuf; +using Grpc.Core; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// +/// H2 consumer side of remote history (plan §3.2, §3.3). The connection sends history on a call only when +/// the selected endpoint advertised it; each call's deadline is min(the caller's remaining budget, the connection's +/// HistoryTimeoutMilliseconds); FAILED_PRECONDITION / UNIMPLEMENTED (a v1 origin, or one without a historian) +/// answer BadHistoryOperationUnsupported. A fresh read may move endpoint; a RESUMED read never moves — its +/// token is wrapped with the endpoint and serving incarnation that issued it. Transport chunks are assembled here +/// within the request's byte budget, so a caller never sees . +/// +public sealed partial class GrpcDataConnection : IDataHistoryService +{ + internal const uint BadHistoryOperationUnsupported = 0x80720000u; + internal const uint BadContinuationPointInvalid = 0x804A0000u; + internal const uint BadTooManyOperations = 0x80100000u; + internal const uint BadTimeout = 0x800A0000u; + internal const uint BadNoCommunication = 0x80310000u; + private const byte EnvelopeTag = 0xC7, EnvelopeVersion = 1; + + private TimeSpan _historyTimeout = TimeSpan.FromSeconds(30); + + /// The per-call history ceiling (the connection's HistoryTimeoutMilliseconds). + public TimeSpan HistoryTimeout + { + get => _historyTimeout; + init => _historyTimeout = value > TimeSpan.Zero ? value : throw new ArgumentOutOfRangeException(nameof(value)); + } + + /// The features this consumer understands; sent on every capabilities probe (coordinator decision, plan §4.1). + internal const DataFeatures ClientFeatures = DataFeatures.History; + + // Explicit: IDataReadService.ReadAsync(ReadRequest) shares the name, and target-typed `new(...)` callers must stay unambiguous. + Task> IDataHistoryService.ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) => + ReadHistoryAsync(request, cancellationToken); + Task IDataHistoryService.ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) => + ReleaseHistoryAsync(continuations, cancellationToken); + + /// Remote HistoryRead (). + public async Task> ReadHistoryAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Items); + request.Budget.Validate(); + var start = Clock.GetTimestamp(); + EnterWork(); + var admitted = false; + try + { + using var admission = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, _shutdown.Token); + admitted = await _unaryCapacity.WaitAsync(0, admission.Token).ConfigureAwait(false); + if (!admitted) return All(request, BadTooManyOperations); + // A resumed item pins the endpoint (and serving incarnation) that issued its token. + var results = new DataHistoryReadResult?[request.Items.Count]; + var items = new DataHistoryReadItem[request.Items.Count]; + int? pinned = null; string? pinnedServing = null; + for (var i = 0; i < items.Length; i++) + { + var item = request.Items[i]; + items[i] = item; + if (item.Continuation is null) continue; + if (!TryUnwrap(item.Continuation, out var endpoint, out var serving, out var token) + || (pinned is { } p && (p != endpoint || pinnedServing != serving)) || endpoint >= _endpoints.Length) + { results[i] = new(item.CorrelationId, BadContinuationPointInvalid, [], null); continue; } + pinned = endpoint; pinnedServing = serving; + items[i] = item with { Continuation = token }; + } + var pending = Enumerable.Range(0, items.Length).Where(i => results[i] is null).ToArray(); + if (pending.Length == 0) return results.Select(x => x!).ToArray(); + var candidates = pinned is { } fixedIndex ? [fixedIndex] : Enumerable.Range(0, _endpoints.Length).ToArray(); + Exception? failure = null; + foreach (var index in candidates) + { + Check(); + Selected selected; + try { selected = await SelectAsync(_endpoints[index], start, request.Budget, false, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); } + catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException) + { failure = ex; RecordFailure(ex); continue; } + if (pinnedServing is not null && pinnedServing != selected.Capabilities.Serving.Incarnation) + { + // The issuing endpoint restarted or failed over: its tokens are gone; never resume elsewhere. + foreach (var i in pending.Where(i => request.Items[i].Continuation is not null)) + results[i] = new(request.Items[i].CorrelationId, BadContinuationPointInvalid, [], null); + pending = pending.Where(i => results[i] is null).ToArray(); + if (pending.Length == 0) return results.Select(x => x!).ToArray(); + } + if (RequestedFeatures(selected.Capabilities) == DataFeatures.None || !selected.Capabilities.Operations.HasFlag(DataOperations.HistoryRead)) + { + foreach (var i in pending) results[i] = new(request.Items[i].CorrelationId, BadHistoryOperationUnsupported, [], null); + return results.Select(x => x!).ToArray(); + } + var served = await ServeAsync(selected, index, request, items, pending, start, cancellationToken).ConfigureAwait(false); + if (served is null) { failure ??= new InvalidOperationException("History endpoint unavailable."); if (pinned is null) continue; break; } + for (var k = 0; k < pending.Length; k++) results[pending[k]] = served[k]; + return results.Select(x => x!).ToArray(); + } + if (failure is not null && pinned is null) ProbeFailed(); + foreach (var i in pending) results[i] = new(request.Items[i].CorrelationId, + pinned is null ? BadNoCommunication : BadContinuationPointInvalid, [], null); + return results.Select(x => x!).ToArray(); + } + finally { if (admitted) _unaryCapacity.Release(); ExitWork(); } + } + + /// Reads on one selected endpoint and assembles its chunks; null = the endpoint failed before answering (a fresh read may move). + private async Task ServeAsync(Selected selected, int endpoint, DataHistoryReadRequest request, + DataHistoryReadItem[] items, int[] pending, long start, CancellationToken cancellationToken) + { + var batch = pending.Select(i => items[i]).ToArray(); + var assembled = new List[batch.Length]; + var final = new DataHistoryReadResult?[batch.Length]; + var completed = new bool[batch.Length]; + long assembledBytes = 0; + var current = batch; + var map = Enumerable.Range(0, batch.Length).ToArray(); + var first = true; + try + { + while (current.Length > 0) + { + var remaining = request.Budget.Timeout - Clock.GetElapsedTime(start); + if (remaining <= TimeSpan.Zero) + { + foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadTimeout, [], null); + break; + } + var deadline = remaining < HistoryTimeout ? remaining : HistoryTimeout; + var wire = DataHistoryProtoMapper.EncodeRequest(request with { Items = current, Budget = request.Budget with { Timeout = deadline } }); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token); + W.HistoryReadResponse response; + try + { + response = await selected.Channel.Client.HistoryReadAsync(wire, new CallOptions( + Headers(selected.Channel, RequestedFeatures(selected.Capabilities)), DateTime.UtcNow + deadline, linked.Token)) + .ResponseAsync.ConfigureAwait(false); + } + catch (RpcException ex) when (ex.StatusCode is StatusCode.FailedPrecondition or StatusCode.Unimplemented) + { + foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadHistoryOperationUnsupported, [], null); + break; + } + catch (RpcException ex) when (ex.StatusCode == StatusCode.DeadlineExceeded && !cancellationToken.IsCancellationRequested) + { + foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadTimeout, [], null); + break; + } + catch (RpcException ex) when (first && ex.StatusCode is StatusCode.Unavailable or StatusCode.Unauthenticated or StatusCode.PermissionDenied + && !cancellationToken.IsCancellationRequested) + { RecordFailure(ex); return null; } + catch (RpcException ex) when (ex.StatusCode != StatusCode.Cancelled || !cancellationToken.IsCancellationRequested) + { + RecordFailure(ex); + foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadNoCommunication, [], null); + break; + } + first = false; + Verify(response.Serving, selected); + var decoded = DataHistoryProtoMapper.DecodeResponse(response, Limits(request.Budget, selected.Capabilities) with + { MaxValueElements = int.MaxValue, MaxBytes = _maxMessageBytes }); + if (decoded.Count != current.Length || decoded.Where((r, k) => r.CorrelationId != current[k].CorrelationId).Any()) + { + foreach (var r in decoded) r.Dispose(); + throw new InvalidOperationException("History response has unexpected items."); + } + var nextItems = new List(); + var nextMap = new List(); + for (var k = 0; k < decoded.Count; k++) + { + var target = map[k]; + var result = decoded[k]; + assembled[target] ??= []; + foreach (var sample in result.Samples) assembledBytes += sample.Value.EstimatedRetainedBytes; + assembled[target].AddRange(result.Samples); + if (assembledBytes > request.Budget.MaxBytes) + { + // The per-request assembly budget is exhausted: this and every later node is BadTooManyOperations. + _ = ReleaseOnEndpointAsync(selected, result.Continuation); + final[target] = new(result.CorrelationId, BadTooManyOperations, [], null, "History assembly budget exceeded."); + continue; + } + if (result.ChunkContinues) + { + nextItems.Add(current[k] with { Continuation = result.Continuation }); + nextMap.Add(target); + continue; + } + final[target] = new(result.CorrelationId, result.StatusCode, [], Wrap(endpoint, selected.Capabilities.Serving.Incarnation, result.Continuation), + result.Diagnostic); + completed[target] = true; + } + current = nextItems.ToArray(); + map = nextMap.ToArray(); + } + var answers = new DataHistoryReadResult[batch.Length]; + for (var k = 0; k < batch.Length; k++) + { + var result = final[k] ?? new(batch[k].CorrelationId, BadNoCommunication, [], null); + if (!completed[k]) + { + // Never hand back a partially assembled answer under an error status. + foreach (var sample in assembled[k] ?? []) sample.Dispose(); + answers[k] = result; + continue; + } + answers[k] = result with { Samples = (IReadOnlyList?)assembled[k] ?? [] }; + } + return answers; + } + catch + { + foreach (var list in assembled) foreach (var sample in list ?? []) sample.Dispose(); + throw; + } + } + + /// Releases continuations on their issuing endpoints (); best effort. + public async Task ReleaseHistoryAsync(IReadOnlyList continuations, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(continuations); + foreach (var group in continuations.Select(x => TryUnwrap(x, out var endpoint, out var serving, out var token) + ? (Endpoint: endpoint, Serving: serving, Token: token) : (Endpoint: -1, Serving: "", Token: Array.Empty())) + .Where(x => x.Endpoint >= 0 && x.Endpoint < _endpoints.Length).GroupBy(x => x.Endpoint)) + { + try + { + var start = Clock.GetTimestamp(); + var budget = new DataBudget(HistoryTimeout, Math.Max(1, group.Count()), _maxMessageBytes); + var selected = await SelectAsync(_endpoints[group.Key], start, budget, false, cancellationToken).ConfigureAwait(false); + if (RequestedFeatures(selected.Capabilities) == DataFeatures.None) continue; + foreach (var token in group.Where(x => x.Serving == selected.Capabilities.Serving.Incarnation)) + await ReleaseOnEndpointAsync(selected, token.Token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException) + { RecordFailure(ex); } // best effort; origin idle expiry is the backstop + } + } + + private async Task ReleaseOnEndpointAsync(Selected selected, byte[]? token) + { + if (token is null) return; + try + { + // Release needs a view only to be well-formed; the origin drops the token without resolving it. + var view = new DataView(new DataAddress(Target.ExpectedClusterId, "urn:release", "string", "release"), DataRealm.Raw, null, 0, "release"); + var wire = DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest(new DataHistoryRawDetails(null, null, 0, false), + [new DataHistoryReadItem("release", view, null, token)], new DataBudget(HistoryTimeout, 1, _maxMessageBytes)), releaseContinuations: true); + await selected.Channel.Client.HistoryReadAsync(wire, new CallOptions(Headers(selected.Channel, RequestedFeatures(selected.Capabilities)), + DateTime.UtcNow + HistoryTimeout, _shutdown.Token)).ResponseAsync.ConfigureAwait(false); + } + catch (Exception ex) when (ex is RpcException or OperationCanceledException or InvalidOperationException) { } + } + + private static DataHistoryReadResult[] All(DataHistoryReadRequest request, uint status) => + request.Items.Select(x => new DataHistoryReadResult(x.CorrelationId, status, [], null)).ToArray(); + + /// [tag][version][endpoint][len:u16][serving incarnation utf8][origin token]. + internal static byte[]? Wrap(int endpoint, string serving, byte[]? token) + { + if (token is null) return null; + var servingBytes = Encoding.UTF8.GetBytes(serving); + if (endpoint is < 0 or > byte.MaxValue || servingBytes.Length > ushort.MaxValue) throw new ArgumentOutOfRangeException(nameof(endpoint)); + var envelope = new byte[5 + servingBytes.Length + token.Length]; + envelope[0] = EnvelopeTag; envelope[1] = EnvelopeVersion; envelope[2] = (byte)endpoint; + BinaryPrimitives.WriteUInt16BigEndian(envelope.AsSpan(3), (ushort)servingBytes.Length); + servingBytes.CopyTo(envelope, 5); + token.CopyTo(envelope, 5 + servingBytes.Length); + return envelope; + } + + internal static bool TryUnwrap(byte[] envelope, out int endpoint, out string serving, out byte[] token) + { + endpoint = -1; serving = ""; token = []; + if (envelope.Length < 6 || envelope[0] != EnvelopeTag || envelope[1] != EnvelopeVersion) return false; + var length = BinaryPrimitives.ReadUInt16BigEndian(envelope.AsSpan(3)); + if (envelope.Length <= 5 + length) return false; + endpoint = envelope[2]; + serving = Encoding.UTF8.GetString(envelope, 5, length); + token = envelope.AsSpan(5 + length).ToArray(); + return true; + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs index 17d669bc2..c23e1253a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs @@ -213,13 +213,14 @@ public sealed partial class GrpcDataConnection : IDataConnection } /// /// The optional features to request from the SELECTED endpoint: only what that endpoint advertised, re-derived on - /// every selection so a failover follows the new endpoint. X0 reserves the negotiation; no capability field - /// advertises a feature yet, so this is always empty and the header is never sent. + /// every selection so a failover follows the new endpoint: this consumer's features ∩ what that endpoint's + /// capabilities advertised (H2: history iff is present). The capabilities + /// PROBE itself always carries (coordinator decision, plan §4.1). /// internal static DataFeatures RequestedFeatures(DataCapabilities capabilities) { ArgumentNullException.ThrowIfNull(capabilities); - return DataFeatures.None; + return capabilities.History is not null ? ClientFeatures & DataFeatures.History : DataFeatures.None; } private Metadata Headers(ChannelEntry channel, DataFeatures features = DataFeatures.None) { @@ -246,8 +247,9 @@ public sealed partial class GrpcDataConnection : IDataConnection { var channel = await ChannelAsync(endpoint, ct).ConfigureAwait(false); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, channel.Retired.Token, _shutdown.Token); + // The probe asks for every feature this consumer understands; the endpoint answers with what it can serve. var response = await channel.Client.GetCapabilitiesAsync(new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 5 }, - Options(channel, start, budget, linked.Token)).ResponseAsync.ConfigureAwait(false); + new CallOptions(Headers(channel, ClientFeatures), DateTime.UtcNow + Remaining(start, budget), linked.Token)).ResponseAsync.ConfigureAwait(false); if (response.ValueKinds.Count > MaxCapabilityKinds || response.ValueKinds.Distinct().Count() != response.ValueKinds.Count) throw new ArgumentException("Invalid capability value kinds."); var caps = DataProtoMapper.DecodeCapabilities(response, new DataDecodeLimits(MaxCapabilityKinds, _maxMessageBytes)); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs index e4433f8e7..edba25926 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs @@ -33,10 +33,14 @@ public sealed class LocalDataConnection : IDataConnection, IDataConnectionPublic /// Direct runtime-consumer history (H2): this facade is the channel, so its origin continuations live only as long as /// the facade and are cleared on . Answers are never chunked. /// - public Task> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) + public Task> ReadHistoryAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) { Check(); return _services.ReadHistoryAsync(_context, Target, request, OwnChannel, chunked: false, cancellationToken); } - public Task ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) + public Task ReleaseHistoryAsync(IReadOnlyList continuations, CancellationToken cancellationToken) { Check(); return _services.ReleaseHistoryAsync(_context, continuations, OwnChannel, cancellationToken); } + Task> IDataHistoryService.ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) => + ReadHistoryAsync(request, cancellationToken); + Task IDataHistoryService.ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) => + ReleaseHistoryAsync(continuations, cancellationToken); /// public Task> ReadForTransportAsync(DataHistoryReadRequest request, DataHistoryChannel channel, CancellationToken cancellationToken) diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs index f73118526..cac2bce63 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs @@ -256,7 +256,8 @@ public sealed class GrpcDataArtifactReadTests [Theory] [InlineData(1073741824, 0)] [InlineData(5 | 1073741824, 5)] - [InlineData(5 | 32, 5)] + [InlineData(5 | 64, 5)] // 64 (AlarmSubscribe) is still reserved; 32 became understood in H2 + [InlineData(5 | 32 | 64, 5 | 32)] public void Unknown_operation_bit_on_a_connection_or_export_parses_and_grants_nothing(int authored, int understood) { var root = Fixture(); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs index 26f6ed984..b9a1cd795 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs @@ -232,11 +232,11 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver); var attempt = Prepare(coordinator, Artifact()); - var enabled = TestMapping(); enabled.AllowedOperations = DataOperations.Browse | DataOperations.HistoryRead; + var enabled = TestMapping(); enabled.AllowedOperations = DataOperations.Browse | DataOperations.AlarmConfirm; var disabled = TestMapping(); disabled.RemoteNamespaceMappingId = "off"; disabled.BranchName = "Off"; disabled.Enabled = false; disabled.AllowedOperations = DataOperations.Browse | DataOperations.AlarmSubscribe; runtime.Stage(attempt, [enabled, disabled], [TestConnection()]); - runtime.DroppedUnknownOperations.ShouldBe(new Dictionary { ["map"] = DataOperations.HistoryRead }); + runtime.DroppedUnknownOperations.ShouldBe(new Dictionary { ["map"] = DataOperations.AlarmConfirm }); runtime.CaptureDroppedByConnection().ShouldBe(new Dictionary { ["link"] = 1 }); coordinator.Complete(attempt, true).ShouldBeTrue(); runtime.Active.ShouldHaveSingleItem().Mapping.AllowedOperations.ShouldBe(DataOperations.Browse); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFeatureHeaderClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFeatureHeaderClientTests.cs index 65d1e8c37..1b5469a7f 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFeatureHeaderClientTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFeatureHeaderClientTests.cs @@ -32,7 +32,7 @@ public sealed class GrpcDataFeatureHeaderClientTests } [Fact] - public async Task No_rpc_carries_the_feature_header_in_X0() + public async Task Without_an_advertised_feature_only_the_capabilities_probe_carries_the_header() { var handler = new RecordingHandler(); using var manager = new DataConnectionManager("consumer", 1); @@ -52,20 +52,25 @@ public sealed class GrpcDataFeatureHeaderClientTests handler.Paths.ShouldContain(p => p.EndsWith("/GetMetadata", StringComparison.Ordinal)); handler.Paths.ShouldContain(p => p.EndsWith("/Read", StringComparison.Ordinal)); handler.Paths.ShouldContain(p => p.EndsWith("/Write", StringComparison.Ordinal)); - handler.FeatureHeaders.ShouldBeEmpty(); + // H2 (coordinator decision): the probe always asks for what this consumer understands; nothing else carries the + // header, because this origin advertised no history field. + handler.FeatureHeaders.ShouldNotBeEmpty(); + handler.FeatureHeaders.ShouldAllBe(x => x == "history"); + handler.FeatureHeaderPaths.ShouldAllBe(p => p.EndsWith("/GetCapabilities", StringComparison.Ordinal)); } private sealed class RecordingHandler : HttpMessageHandler { public List Paths { get; } = []; public List FeatureHeaders { get; } = []; + public List FeatureHeaderPaths { get; } = []; protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var path = request.RequestUri!.AbsolutePath; lock (Paths) { Paths.Add(path); - if (request.Headers.TryGetValues("x-otopcua-data-features", out var values)) FeatureHeaders.AddRange(values); + if (request.Headers.TryGetValues("x-otopcua-data-features", out var values)) { FeatureHeaders.AddRange(values); FeatureHeaderPaths.Add(path); } } IMessage message; if (path.EndsWith("/GetCapabilities", StringComparison.Ordinal)) @@ -79,7 +84,7 @@ public sealed class GrpcDataFeatureHeaderClientTests { var wire = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, new DataMetadata(View, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Read | DataOperations.Write, 1, null, null, false), null)]); - wire.Items[0].Value.AllowedOperations |= 32u; + wire.Items[0].Value.AllowedOperations |= 64u; // still reserved (32 is understood since H2) wire.Serving = DataProtoMapper.EncodeServing(Serving); message = wire; } else if (path.EndsWith("/Read", StringComparison.Ordinal)) diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs new file mode 100644 index 000000000..c0e653955 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs @@ -0,0 +1,248 @@ +using System.Buffers.Binary; +using System.Net; +using Google.Protobuf; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// H2 consumer: as an — header only toward an +/// endpoint that advertised history, unsupported answers, per-call deadline = min(remaining, HistoryTimeout), chunk +/// assembly within the request budget, a resumed read pinned to its issuing endpoint, release forwarding. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H2")] +public sealed class GrpcDataHistoryClientTests +{ + private static readonly DataLimits Limits = new(16, 16, 1 << 20, 16, 4, 1 << 20, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)); + private static readonly DataView View = new(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x"); + private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(20), 16, 1 << 22); + private static readonly DataHistoryCapabilities Caps = new(true, true, true, ["Average"], 1, 100, 4, TimeSpan.FromSeconds(60)); + + private static DataHistoryReadRequest Request(byte[]? continuation = null) => + new(new DataHistoryRawDetails(null, DateTimeOffset.UnixEpoch.AddDays(1), 2, false), [new("a", View, null, continuation)], Budget); + + [Fact] + public async Task An_origin_without_history_answers_unsupported_and_no_HistoryRead_rpc_is_sent() + { + var a = new Endpoint("a", history: false); + await using var connection = Connect([a]); + var results = await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken); + results.Single().StatusCode.ShouldBe(0x80720000u); + a.HistoryCalls.ShouldBe(0); + a.Headers.ShouldAllBe(x => x.Path.EndsWith("/GetCapabilities", StringComparison.Ordinal) && x.Features == "history"); + } + + [Fact] + public async Task Failed_precondition_from_the_origin_is_unsupported_never_a_transport_fault() + { + var a = new Endpoint("a") { Fail = Grpc.Core.StatusCode.FailedPrecondition }; + await using var connection = Connect([a]); + (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x80720000u); + var b = new Endpoint("b") { Fail = Grpc.Core.StatusCode.Unimplemented }; + await using var v1 = Connect([b]); + (await v1.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x80720000u); + } + + [Fact] + public async Task The_header_and_the_deadline_follow_the_advertised_endpoint_and_HistoryTimeout() + { + var a = new Endpoint("a"); + await using var connection = Connect([a], historyTimeout: TimeSpan.FromSeconds(2)); + var results = await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken); + results.Single().StatusCode.ShouldBe(0u); + results.Single().Samples.Count.ShouldBe(2); + a.Headers.Where(x => x.Path.EndsWith("/HistoryRead", StringComparison.Ordinal)).ShouldAllBe(x => x.Features == "history"); + a.LastTimeout.ShouldNotBeNull(); + a.LastTimeout!.Value.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(2.5), "min(remaining 20 s, HistoryTimeout 2 s)"); + a.LastBudgetTimeout.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(2)); + foreach (var r in results) r.Dispose(); + } + + [Fact] + public async Task Chunks_are_assembled_and_the_page_continuation_is_wrapped_with_its_endpoint() + { + var a = new Endpoint("a") { Chunks = 3, PageToken = [9, 9, 9] }; + await using var connection = Connect([a]); + var result = (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single(); + result.ChunkContinues.ShouldBeFalse(); + result.Samples.Count.ShouldBe(6, "three chunks of two"); + a.HistoryCalls.ShouldBe(3); + GrpcDataConnection.TryUnwrap(result.Continuation!, out var endpoint, out var serving, out var token).ShouldBeTrue(); + endpoint.ShouldBe(0); serving.ShouldBe("boot-a"); token.ShouldBe(new byte[] { 9, 9, 9 }); + result.Dispose(); + } + + [Fact] + public async Task Exceeding_the_assembly_budget_is_BadTooManyOperations() + { + var a = new Endpoint("a") { Chunks = 50 }; + await using var connection = Connect([a]); + var tight = Request() with { Budget = Budget with { MaxBytes = 2048 } }; + (await connection.ReadHistoryAsync(tight, TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x80100000u); + } + + [Fact] + public async Task A_fresh_read_may_move_endpoint_but_a_resumed_read_never_does() + { + var a = new Endpoint("a") { Unavailable = true }; + var b = new Endpoint("b") { PageToken = [1, 2, 3] }; + await using var connection = Connect([a, b]); + var fresh = (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single(); + fresh.StatusCode.ShouldBe(0u, "the fresh read moved to b"); + var token = fresh.Continuation!; + GrpcDataConnection.TryUnwrap(token, out var endpoint, out _, out _).ShouldBeTrue(); + endpoint.ShouldBe(1); + // b now fails; a resume must not move to a (which would not know the token). + b.Unavailable = true; a.Unavailable = false; + var resumed = (await connection.ReadHistoryAsync(Request(token), TestContext.Current.CancellationToken)).Single(); + resumed.StatusCode.ShouldBe(0x804A0000u); + a.HistoryCalls.ShouldBe(0); + // b came back under a new incarnation (restart/failover): its old tokens are invalid without asking it. + b.Unavailable = false; b.Incarnation = "boot-b2"; + var after = (await connection.ReadHistoryAsync(Request(token), TestContext.Current.CancellationToken)).Single(); + after.StatusCode.ShouldBe(0x804A0000u); + b.LastContinuations.ShouldBeEmpty(); + fresh.Dispose(); + } + + [Fact] + public async Task A_resumed_read_sends_the_origins_own_token_and_release_forwards_it_to_the_issuing_endpoint() + { + var a = new Endpoint("a") { PageToken = [4, 5, 6] }; + await using var connection = Connect([a]); + var first = (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single(); + (await connection.ReadHistoryAsync(Request(first.Continuation), TestContext.Current.CancellationToken)).Single().Dispose(); + a.LastContinuations.Single().ShouldBe(new byte[] { 4, 5, 6 }, "the envelope is unwrapped before it goes on the wire"); + await connection.ReleaseHistoryAsync([first.Continuation!], TestContext.Current.CancellationToken); + a.Released.Single().ShouldBe(new byte[] { 4, 5, 6 }); + // A malformed token is invalid locally. + (await connection.ReadHistoryAsync(Request([1, 2]), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x804A0000u); + first.Dispose(); + } + + private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? historyTimeout = null) + { + var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + var router = new Router(endpoints); + return new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), endpoints.Select(e => new Uri($"https://{e.Name}.test")), + new Security(router), manager.Acquire("link"), 1 << 22, endpoints.Length, + eligibleNodeIds: endpoints.Select(e => e.Name).ToHashSet()) { HistoryTimeout = historyTimeout ?? TimeSpan.FromSeconds(30) }; + } + + internal sealed class Endpoint(string name, bool history = true) + { + public string Name { get; } = name; + public string Incarnation { get; set; } = "boot-" + name; + public bool Unavailable { get; set; } + public Grpc.Core.StatusCode? Fail { get; init; } + public int Chunks { get; init; } = 1; + public byte[]? PageToken { get; init; } + public int HistoryCalls; + public List<(string Path, string? Features)> Headers { get; } = []; + public List LastContinuations { get; private set; } = []; + public List Released { get; } = []; + public TimeSpan? LastTimeout { get; private set; } + public TimeSpan LastBudgetTimeout { get; private set; } + private readonly Dictionary _chunkLeft = new(); + + public ServingIdentity Serving => new(Name, Incarnation, "Primary", 1, 1, 1); + + public async Task HandleAsync(HttpRequestMessage request, CancellationToken token) + { + var path = request.RequestUri!.AbsolutePath; + lock (Headers) Headers.Add((path, request.Headers.TryGetValues("x-otopcua-data-features", out var v) ? string.Join(",", v) : null)); + if (Unavailable) return Status(Grpc.Core.StatusCode.Unavailable); + IMessage message; + if (path.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + { + var asked = request.Headers.Contains("x-otopcua-data-features"); + var caps = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 5, Serving, DataReadiness.Ready, + DataOperationSets.V1 | (history && asked ? DataOperations.HistoryRead : DataOperations.None), + new HashSet { DataValueKind.Double }, Limits, false, 0, "c", true, true, true, true, true, + history && asked ? Caps : null)); + message = caps; + } + else + { + Interlocked.Increment(ref HistoryCalls); + if (Fail is { } fail) return Status(fail); + if (request.Headers.TryGetValues("grpc-timeout", out var timeouts)) LastTimeout = ParseTimeout(timeouts.Single()); + var bytes = await request.Content!.ReadAsByteArrayAsync(token); + var wire = W.HistoryReadRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray()); + LastBudgetTimeout = TimeSpan.FromTicks(wire.Budget.TimeoutTicks); + var response = new W.HistoryReadResponse { Serving = DataProtoMapper.EncodeServing(Serving) }; + if (wire.ReleaseContinuations) + { + foreach (var item in wire.Items) Released.Add(item.Continuation.ToByteArray()); + foreach (var item in wire.Items) response.Items.Add(new W.HistoryReadResult { CorrelationId = item.CorrelationId }); + } + else + { + LastContinuations = wire.Items.Where(x => x.HasContinuation).Select(x => x.Continuation.ToByteArray()).ToList(); + foreach (var item in wire.Items) + { + var key = item.CorrelationId; + int left; + lock (_chunkLeft) left = _chunkLeft[key] = item.HasContinuation && _chunkLeft.TryGetValue(key, out var l) && l > 0 ? l - 1 : Chunks - 1; + using var s1 = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 1.0), 0, DateTimeOffset.UnixEpoch, null); + using var s2 = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 2.0), 0, null, null); + var result = new DataHistoryReadResult(key, 0, [s1, s2], left > 0 ? [7, 7] : PageToken, null, left > 0); + response.Items.Add(DataHistoryProtoMapper.EncodeResult(result)); + } + } + message = response; + } + var payload = message.ToByteArray(); var framed = new byte[payload.Length + 5]; + BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); payload.CopyTo(framed, 5); + var ok = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) }; + ok.Content.Headers.ContentType = new("application/grpc"); ok.TrailingHeaders.Add("grpc-status", "0"); + return ok; + } + + private static HttpResponseMessage Status(Grpc.Core.StatusCode code) + { + var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent([]) }; + response.Content.Headers.ContentType = new("application/grpc"); + response.Headers.Add("grpc-status", ((int)code).ToString(System.Globalization.CultureInfo.InvariantCulture)); + response.Headers.Add("grpc-message", code == Grpc.Core.StatusCode.FailedPrecondition ? "feature not negotiated" : "x"); + return response; + } + + private static TimeSpan ParseTimeout(string value) + { + var amount = long.Parse(value[..^1], System.Globalization.CultureInfo.InvariantCulture); + return value[^1] switch + { + 'H' => TimeSpan.FromHours(amount), 'M' => TimeSpan.FromMinutes(amount), 'S' => TimeSpan.FromSeconds(amount), + 'm' => TimeSpan.FromMilliseconds(amount), 'u' => TimeSpan.FromTicks(amount * 10), _ => TimeSpan.FromTicks(amount / 100), + }; + } + } + + private sealed class Router(Endpoint[] endpoints) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + endpoints.Single(e => request.RequestUri!.Host == e.Name + ".test").HandleAsync(request, cancellationToken); + } + + private sealed class Security(HttpMessageHandler handler) : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new("v1", "ca1", "key", () => new NonDisposing(handler))); + } + + // Each channel disposes its handler; the shared router must survive that. + private sealed class NonDisposing(HttpMessageHandler inner) : HttpMessageHandler + { + private readonly HttpMessageInvoker _invoker = new(inner, disposeHandler: false); + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + _invoker.SendAsync(request, cancellationToken); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataUnknownOperationToleranceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataUnknownOperationToleranceTests.cs index 9e8991078..7a90c8646 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataUnknownOperationToleranceTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataUnknownOperationToleranceTests.cs @@ -34,7 +34,7 @@ public sealed class GrpcDataUnknownOperationToleranceTests { var activator = new Activator(); await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); - var history = Definition("history", DataOperations.Read | DataOperations.Browse | DataOperations.HistoryRead | DataOperations.AlarmShelve); + var history = Definition("history", DataOperations.Read | DataOperations.Browse | DataOperations.AlarmConfirm | DataOperations.AlarmShelve); var plain = Definition("plain", DataOperations.Read | DataOperations.Subscribe); var future = Definition("future", (DataOperations)(1 << 30) | DataOperations.AlarmSubscribe); @@ -49,18 +49,18 @@ public sealed class GrpcDataUnknownOperationToleranceTests runtime.DroppedUnknownOperations.ShouldBe(new Dictionary(StringComparer.OrdinalIgnoreCase) { - ["history"] = DataOperations.HistoryRead | DataOperations.AlarmShelve, + ["history"] = DataOperations.AlarmConfirm | DataOperations.AlarmShelve, ["future"] = (DataOperations)(1 << 30) | DataOperations.AlarmSubscribe, }); runtime.UnknownOperationRowsDropped.ShouldBe(2); // The production reader: the node diagnostics snapshot carries each row's dropped bits. var diagnostics = runtime.CaptureDiagnostics().ToDictionary(x => x.ConnectionId); - diagnostics["history"].DroppedUnknownOperations.ShouldBe(DataOperations.HistoryRead | DataOperations.AlarmShelve); + diagnostics["history"].DroppedUnknownOperations.ShouldBe(DataOperations.AlarmConfirm | DataOperations.AlarmShelve); diagnostics["plain"].DroppedUnknownOperations.ShouldBe(DataOperations.None); diagnostics["future"].DroppedUnknownOperations.ShouldBe((DataOperations)(1 << 30) | DataOperations.AlarmSubscribe); diagnostics["plain"].MappingsWithDroppedOperations.ShouldBeNull("no mapping evidence was supplied"); // The input rows are not mutated: the drop is the node's reading, not a rewrite of the artifact. - history.AllowedOperations.ShouldBe(DataOperations.Read | DataOperations.Browse | DataOperations.HistoryRead | DataOperations.AlarmShelve); + history.AllowedOperations.ShouldBe(DataOperations.Read | DataOperations.Browse | DataOperations.AlarmConfirm | DataOperations.AlarmShelve); activator.Allowlists.Last().Keys.Order(StringComparer.OrdinalIgnoreCase).ShouldBe(["future", "history", "plain"]); } @@ -68,7 +68,7 @@ public sealed class GrpcDataUnknownOperationToleranceTests public async Task Reapplying_the_same_revision_does_not_recount_and_a_clean_artifact_clears_the_diagnostic() { await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), new Activator(), 4); - var snapshot = new DataConnectionDeploymentSnapshot(1, "artifact-1", [Definition("history", DataOperations.Read | DataOperations.HistoryRead)]); + var snapshot = new DataConnectionDeploymentSnapshot(1, "artifact-1", [Definition("history", DataOperations.Read | DataOperations.AlarmConfirm)]); runtime.Apply(snapshot); runtime.Apply(snapshot); runtime.UnknownOperationRowsDropped.ShouldBe(1); @@ -79,7 +79,7 @@ public sealed class GrpcDataUnknownOperationToleranceTests runtime.UnknownOperationRowsDropped.ShouldBe(1); // A -> B -> A is an accepted artifact CHANGE each time, so it recounts (documented semantics). - runtime.Apply(new(3, "artifact-1", [Definition("history", DataOperations.Read | DataOperations.HistoryRead)])); + runtime.Apply(new(3, "artifact-1", [Definition("history", DataOperations.Read | DataOperations.AlarmConfirm)])); runtime.UnknownOperationRowsDropped.ShouldBe(2); } @@ -87,15 +87,15 @@ public sealed class GrpcDataUnknownOperationToleranceTests public void Node_side_artifact_parse_accepts_rows_carrying_bits_a_newer_central_authored() { var root = Fixture(); - root["DataConnections"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead); - root["DataExports"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead | DataOperations.AlarmSubscribe); - root["RemoteNamespaceMappings"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.HistoryRead); + root["DataConnections"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Read | DataOperations.AlarmConfirm); + root["DataExports"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Read | DataOperations.AlarmConfirm | DataOperations.AlarmSubscribe); + root["RemoteNamespaceMappings"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.AlarmConfirm); using var parsed = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(root.ToJsonString())); // Pre-X0 each of these threw InvalidDataException through the node-side DataConnectionValidator pass. // Rows come back as authored; each consumer keeps only the bits it understands. parsed.ParseDataConnections("node-a").ShouldHaveSingleItem().AllowedOperations.ShouldBe( - DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead); + DataOperations.Browse | DataOperations.Read | DataOperations.AlarmConfirm); parsed.ParseDataExports("node-b").ShouldHaveSingleItem().DataExportId.ShouldBe("export-a"); parsed.ParseRemoteNamespaceMappings("node-a").ShouldHaveSingleItem().RemoteNamespaceMappingId.ShouldBe("mapping-a"); } @@ -127,7 +127,7 @@ public sealed class GrpcDataUnknownOperationToleranceTests DataExports = [ new() { DataExportId = "history", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "Cluster", - RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead }, + RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Read | DataOperations.AlarmConfirm }, new() { DataExportId = "alarms-only", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = "Cluster", RootEntityId = "cluster", PrincipalId = "other", AllowedOperations = DataOperations.AlarmSubscribe | DataOperations.AlarmAcknowledge }, ], @@ -155,7 +155,7 @@ public sealed class GrpcDataUnknownOperationToleranceTests RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Read, MaxBatchItems = 100, MaxPageItems = 100, MaxMonitoredItems = 100, MaxStreams = 10 }, new() { DataExportId = "future-only", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = "Cluster", - RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.HistoryRead | (DataOperations)(1 << 30), + RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.AlarmConfirm | (DataOperations)(1 << 30), MaxBatchItems = 1, MaxPageItems = 1, MaxMonitoredItems = 1, MaxStreams = 1 }, ], };