From 3c5cbea93102cc8304d9590cc6312bcf3c759e67 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Mon, 23 Nov 2026 22:04:23 -0500 Subject: [PATCH] fix(grpc-data): H2 review 2/3/4/9 - readiness is Ready()'s job; client faults never escape Origin advertises history whenever it has a historian, so a not-ready/demoted endpoint answers HistoryRead Unavailable (ungranted: PermissionDenied) and the consumer fails over like v1 Read instead of 'unsupported'. Client: malformed/undecodable answers are endpoint failures (fresh read moves on); a resumed item is ContinuationPointInvalid while a fresh item of the same batch is BadNoCommunication; a fresh read tries the next endpoint when one lacks history; discovery backoff honoured; origin Cancelled without a caller cancel is BadTimeout (no RecordFailure); caller cancel throws. The deployment lease maps inner/scope faults to BadNoCommunication. The UnaryTimeout cap is documented next to the AdminUI field and in DataConnections.md. --- docs/DataConnections.md | 6 +- .../Clusters/ClusterDataConnections.razor | 2 +- .../DataConnectionDeploymentRuntime.cs | 22 +++++- .../GrpcDataConnection.History.cs | 44 ++++++++---- .../LocalDataServices.History.cs | 12 +++- .../DataConnections/LocalDataServices.cs | 2 +- .../GrpcDataHistoryWireTests.cs | 16 +++++ .../GrpcDataV1RealOriginCompatibilityTests.cs | 6 +- .../GrpcDataHistoryClientTests.cs | 69 ++++++++++++++++++- .../GrpcDataHistoryLeaseTests.cs | 45 ++++++++++++ 10 files changed, 195 insertions(+), 29 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryLeaseTests.cs diff --git a/docs/DataConnections.md b/docs/DataConnections.md index c18a95729..feeb1449b 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -167,10 +167,10 @@ pre-H2 origin, or a call without the header answers unsupported — the v1 respo | Setting | Default | Effect | |---|---|---| -| `DataConnection.HistoryTimeoutMilliseconds` | 30000 | Each call's deadline is the smaller of the caller's remaining budget and this; expiry ⇒ `BadTimeout` | +| `DataConnection.HistoryTimeoutMilliseconds` | 30000 | Each call's deadline is the smaller of the caller's remaining budget and this; expiry ⇒ `BadTimeout`. The origin also cancels every unary call at its own `DataConnections:UnaryTimeout` (30 s default), so the effective ceiling is the smaller of the two; that origin cancel is reported `BadTimeout` too, never an endpoint failure | | `DataExport.MaxConcurrentHistoryReads` | 4 | Concurrent history requests per principal; past it ⇒ `BadTooManyOperations` | -| `DataExport.MaxHistoryValuesPerPage` | 10000 | Per-node page ceiling; an uncapped Raw read pages at it and returns a continuation | -| `DataExport.MaxHistoryResponseBytes` | 4 MiB | Larger answers travel in bounded chunks the consumer reassembles | +| `DataExport.MaxHistoryValuesPerPage` | 10000 | Per-node page ceiling; an uncapped Raw read pages at it and returns a continuation. Processed intervals and AtTime times above it are refused `BadTooManyOperations` before any backend read | +| `DataExport.MaxHistoryResponseBytes` | 4 MiB | Larger answers travel in bounded chunks the consumer reassembles. The origin stops reading once a response is full and serves the remaining nodes on the next chunk call; remainders it holds count against a per-principal byte budget (concurrent reads × max(response limit, one page)) — past it a node is `BadTooManyOperations`, never dropped silently | | `RemoteNamespaceMapping.MaxHistoryAssemblyBytesPerRequest` | 16 MiB | Used by projected reads (H3); a direct consumer's budget is its request `MaxBytes` | **Continuations.** Origin continuations are single-use, idle-expire after 60 s and are bound to the principal, the HTTP/2 diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor index 6c69abd95..2857621c4 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor @@ -73,7 +73,7 @@ else
Reference only; never enter a key or secret value.
Consumer nodes@foreach (var n in Nodes) { }
@Operations(c.AllowedOperations, v => c.AllowedOperations = v) -
Each remote HistoryRead call is bounded by the caller's remaining deadline and this.
+
Each remote HistoryRead call is bounded by the caller's remaining deadline and this, and in addition by the origin's DataConnections:UnaryTimeout (30 s by default): a larger value has no effect past it.
@Actions(c, c.DataConnectionRowId != Guid.Empty) 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 d9c1ff8b1..684a41759 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -527,12 +527,28 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistor // 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); + IReadOnlyList value; + try + { + value = await history.ReadAsync(request with { Budget = request.Budget with { MaxItems = Math.Min(request.Budget.MaxItems, _batch) } }, + cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested && ex is InvalidOperationException or UnauthorizedAccessException) + { + return Unavailable(request); // connection or scope trouble is a per-item communication failure, never an escape + } try { Check(DataOperations.HistoryRead); return value; } - catch { foreach (var item in value) item.Dispose(); throw; } + catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException or OperationCanceledException + && !cancellationToken.IsCancellationRequested) + { + foreach (var item in value) item.Dispose(); + return Unavailable(request); // the scope moved while the answer was in flight + } } + private static DataHistoryReadResult[] Unavailable(DataHistoryReadRequest request) => request.Items + .Select(x => new DataHistoryReadResult(x.CorrelationId, GrpcDataConnection.BadNoCommunication, [], null)).ToArray(); + Task> IDataHistoryService.ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) => ReadHistoryAsync(request, cancellationToken); Task IDataHistoryService.ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) => 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 index f28b06800..1612870ae 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs @@ -73,37 +73,55 @@ public sealed partial class GrpcDataConnection : IDataHistoryService } var pending = Enumerable.Range(0, items.Length).Where(i => results[i] is null).ToArray(); if (pending.Length == 0) return results.Select(x => x!).ToArray(); + bool Resumed(int i) => request.Items[i].Continuation is not null; + DataHistoryReadResult[] Finish(Func status) + { + foreach (var i in pending) results[i] ??= new(request.Items[i].CorrelationId, status(i), [], null); + return results.Select(x => x!).ToArray(); + } + // A fresh read honours discovery backoff like every v1 call; a resumed one goes to its issuing endpoint regardless. + if (pinned is null && !ProbeAllowed()) return Finish(_ => BadNoCommunication); var candidates = pinned is { } fixedIndex ? [fixedIndex] : Enumerable.Range(0, _endpoints.Length).ToArray(); Exception? failure = null; + var unsupported = false; foreach (var index in candidates) { Check(); + cancellationToken.ThrowIfCancellationRequested(); 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) + catch (Exception ex) when (!cancellationToken.IsCancellationRequested + && ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException or ArgumentException) { 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); + foreach (var i in pending.Where(Resumed)) 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(); + // A fresh read tries the other endpoints; a pinned one cannot move. + unsupported = true; + if (pinned is not null) break; + continue; } - 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; } + DataHistoryReadResult[]? served; + try { served = await ServeAsync(selected, index, request, items, pending, start, cancellationToken).ConfigureAwait(false); } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested + && ex is InvalidOperationException or ArgumentException or RpcException or HttpRequestException) + { + // A malformed answer (unexpected items / serving identity, undecodable) is an endpoint failure. + failure = ex; RecordFailure(ex); served = null; + } + if (served is null) { failure ??= new InvalidOperationException("History endpoint unavailable."); if (pinned is not null) break; continue; } 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(); + if (failure is not null && pinned is null && !unsupported) ProbeFailed(); + // Resumed items cannot move; fresh items of the same batch are a communication failure, never an invalid token. + return Finish(i => Resumed(i) ? BadContinuationPointInvalid : unsupported ? BadHistoryOperationUnsupported : BadNoCommunication); } finally { if (admitted) _unaryCapacity.Release(); ExitWork(); } } @@ -145,8 +163,10 @@ public sealed partial class GrpcDataConnection : IDataHistoryService foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadHistoryOperationUnsupported, [], null); break; } - catch (RpcException ex) when (ex.StatusCode == StatusCode.DeadlineExceeded && !cancellationToken.IsCancellationRequested) + catch (RpcException ex) when (ex.StatusCode is StatusCode.DeadlineExceeded or StatusCode.Cancelled && !cancellationToken.IsCancellationRequested) { + // The call's own deadline, or the origin cancelling it at ITS unary timeout (the effective ceiling is + // min(HistoryTimeout, origin DataConnections:UnaryTimeout)): a timeout, never an endpoint failure. foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadTimeout, [], null); break; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs index da9867fd2..a4ad17d4b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs @@ -54,10 +54,16 @@ public sealed partial class LocalDataServices node.Metadata.View.Realm == DataRealm.Raw ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns; /// The caller's history capabilities, when HistoryRead is among its operations. - internal DataHistoryCapabilities? HistoryCapabilitiesFor(LocalExportCatalog? catalog, DataAuthenticatedContext context, DataOperations operations) + /// + /// Present whenever this origin HAS a historian (H2 review): negotiation is header ∩ supported ∩ origin-has-historian, + /// and readiness / grants are answered by the RPC's Ready(…, HistoryRead) (Unavailable / PermissionDenied), so a + /// not-ready or demoted endpoint makes the consumer fail over exactly like a v1 Read, instead of "unsupported". + /// The limits are the principal's export limits, or the schema defaults when no export grants it history. + /// + internal DataHistoryCapabilities? HistoryCapabilitiesFor(LocalExportCatalog? catalog, DataAuthenticatedContext context) { - if ((operations & DataOperations.HistoryRead) == 0 || catalog?.HistoryLimitsFor(context.PrincipalId) is not { } limits - || HistoryServing is not { } serving) return null; + if (HistoryServing is not { } serving) return null; + var limits = catalog?.HistoryLimitsFor(context.PrincipalId) ?? (4, 10_000, 4 * 1024 * 1024); return new DataHistoryCapabilities(true, serving.Aggregates.Count > 0, true, serving.Aggregates, serving.TimestampResolutionTicks, limits.ValuesPerPage, limits.ConcurrentReads, PeerHistoryIdle); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs index 2dbbf0742..ab9943875 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs @@ -233,7 +233,7 @@ public sealed partial class LocalDataServices : IDataConnectionFactory if (catalog is null || !Ready(catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving)) capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None }; // H2: the transport strips History (and the bit) from a call that did not negotiate history. - capabilities = capabilities with { History = HistoryCapabilitiesFor(catalog, context, capabilities.Operations) }; + capabilities = capabilities with { History = HistoryCapabilitiesFor(catalog, context) }; return Task.FromResult(capabilities with { WriteServingGenerationEnforced = true, SubscriptionAgeReadiness = true, ResponseServingIdentity = true, SubscriptionFreshnessChallenges = _subscriptionFreshnessChallenges, MetadataItemLeases = true, ProtocolMinor = Math.Max(5, capabilities.ProtocolMinor) }); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs index 3ed4df031..3dd02e08a 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs @@ -268,6 +268,22 @@ public sealed class GrpcDataHistoryWireTests DataConnectionGrpcService.CallFeatures(refused).ShouldBe(new DataCallFeatures(DataFeatures.History, DataFeatures.None)); } + [Fact] + public async Task A_not_ready_or_demoted_history_capable_origin_answers_Unavailable_not_FailedPrecondition() + { + // Negotiation = header ∩ supported ∩ origin-has-historian; readiness is Ready()'s job, so the client fails over like v1. + await using var demoted = new RealOrigin(role: "Secondary"); + var failure = await Should.ThrowAsync(() => demoted.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History)); + failure.StatusCode.ShouldBe(StatusCode.Unavailable); + var probe = W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(await demoted.DriveAsync("GetCapabilities", History))); + probe.History.ShouldNotBeNull("the historian is there; the node is just not ready for this target"); + probe.Readiness.ShouldBe((int)DataReadiness.Unavailable); + // An origin whose export grants no HistoryRead to this peer is PermissionDenied, as v1 Read is without a Read grant. + await using var ungranted = new RealOrigin(exportOperations: DataOperationSets.V1, grantHistory: false); + var denied = await Should.ThrowAsync(() => ungranted.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History)); + denied.StatusCode.ShouldBe(StatusCode.PermissionDenied); + } + [Fact] public async Task Origin_memory_is_bounded_per_request_and_per_principal_and_nothing_is_lost() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs index f43853e49..7dcd7e2ba 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs @@ -251,7 +251,7 @@ internal sealed class RealOrigin : IAsyncDisposable internal FakeHistoryPort? History { get; } internal RealOrigin(DataOperations exportOperations = DataOperationSets.V1, bool historian = true, int concurrentReads = 4, - int responseBytes = 4 * 1024 * 1024, NodePermissions permissions = NodePermissions.Operator, int valuesPerPage = 10_000) + int responseBytes = 4 * 1024 * 1024, NodePermissions permissions = NodePermissions.Operator, int valuesPerPage = 10_000, string role = "Primary", bool grantHistory = true) { History = historian ? new FakeHistoryPort() : null; var fence = new DataWriteDispatchFence(); @@ -265,10 +265,10 @@ internal sealed class RealOrigin : IAsyncDisposable var epoch = activation.Begin("rev-1"); activation.AuthorityInstalled(epoch, authority.Current.GenerationId); activation.Complete(epoch, true); - Serving = new ServingIdentity("node-a", Incarnation, "Primary", epoch, authority.Current.GenerationId, 1); + Serving = new ServingIdentity("node-a", Incarnation, role, epoch, authority.Current.GenerationId, 1); if (Serving.CatalogEpoch != CatalogEpoch) throw new InvalidOperationException("Catalog epoch is no longer deterministic."); // H2 new-shape data: every export also grants HistoryRead (header-less callers must never see it). - var catalog = LocalExportCatalog.Compile(Snapshot(exportOperations | DataOperations.HistoryRead, concurrentReads, responseBytes, valuesPerPage), + var catalog = LocalExportCatalog.Compile(Snapshot(grantHistory ? exportOperations | DataOperations.HistoryRead : exportOperations, concurrentReads, responseBytes, valuesPerPage), Serving, activation.CaptureAuthority()); _hub = new PartitionedSampleHub(new DataResourceLimits 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 index c0e653955..f12c1703a 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs @@ -125,6 +125,65 @@ public sealed class GrpcDataHistoryClientTests first.Dispose(); } + [Fact] + public async Task A_fresh_read_moves_past_a_not_ready_or_ungranted_endpoint() + { + var a = new Endpoint("a") { Ready = false }; + var b = new Endpoint("b") { Granted = false }; + var c = new Endpoint("c"); + await using var connection = Connect([a, b, c]); + var result = (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single(); + result.StatusCode.ShouldBe(0u); + c.HistoryCalls.ShouldBe(1); + (a.HistoryCalls + b.HistoryCalls).ShouldBe(0); + result.Dispose(); + // Every endpoint without history ⇒ unsupported. + c.Granted = false; + (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x80720000u); + } + + [Fact] + public async Task A_malformed_answer_is_an_endpoint_failure_for_a_fresh_read_and_never_escapes() + { + var a = new Endpoint("a") { Malformed = true }; + var b = new Endpoint("b") { PageToken = [3] }; + await using var connection = Connect([a, b]); + var fresh = (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single(); + fresh.StatusCode.ShouldBe(0u, "moved to b"); + // b now answers malformed: the resumed item is ContinuationPointInvalid, a fresh item in the same batch is not. + b.Malformed = true; + var mixed = new DataHistoryReadRequest(Request().Details, + [new("resumed", View, null, fresh.Continuation), new("fresh", View)], Budget); + var results = await connection.ReadHistoryAsync(mixed, TestContext.Current.CancellationToken); + results[0].StatusCode.ShouldBe(0x804A0000u); + results[1].StatusCode.ShouldBe(0x80310000u); + fresh.Dispose(); + } + + [Fact] + public async Task A_server_cancel_without_a_caller_cancel_is_BadTimeout_and_a_caller_cancel_throws() + { + var a = new Endpoint("a") { Fail = Grpc.Core.StatusCode.Cancelled }; + await using var connection = Connect([a]); + (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x800A0000u); + (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x800A0000u, + "a server-side timeout is not an endpoint failure (no discovery backoff)"); + using var cancelled = new CancellationTokenSource(); + await cancelled.CancelAsync(); + await Should.ThrowAsync(() => connection.ReadHistoryAsync(Request(), cancelled.Token)); + } + + [Fact] + public async Task Discovery_backoff_is_honoured_on_the_history_path() + { + var a = new Endpoint("a") { Unavailable = true }; + await using var connection = Connect([a]); + (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x80310000u); + var probes = a.Headers.Count; + (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x80310000u); + a.Headers.Count.ShouldBe(probes, "backing off: no new probe"); + } + private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? historyTimeout = null) { var manager = new DataConnectionManager("consumer", 1); @@ -140,7 +199,10 @@ public sealed class GrpcDataHistoryClientTests 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 Grpc.Core.StatusCode? Fail { get; set; } + public bool Ready { get; set; } = true; + public bool Granted { get; set; } = true; + public bool Malformed { get; set; } public int Chunks { get; init; } = 1; public byte[]? PageToken { get; init; } public int HistoryCalls; @@ -162,8 +224,8 @@ public sealed class GrpcDataHistoryClientTests 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), + var caps = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 5, Serving, Ready ? DataReadiness.Ready : DataReadiness.Unavailable, + !Ready ? DataOperations.None : DataOperationSets.V1 | (history && asked && Granted ? DataOperations.HistoryRead : DataOperations.None), new HashSet { DataValueKind.Double }, Limits, false, 0, "c", true, true, true, true, true, history && asked ? Caps : null)); message = caps; @@ -194,6 +256,7 @@ public sealed class GrpcDataHistoryClientTests 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)); + if (Malformed) response.Items[^1].CorrelationId = "not-" + key; } } message = response; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryLeaseTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryLeaseTests.cs new file mode 100644 index 000000000..82199a91f --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryLeaseTests.cs @@ -0,0 +1,45 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// H2 review 3: the deployment lease never lets a history fault escape as an exception. +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H2")] +public sealed class GrpcDataHistoryLeaseTests +{ + private static readonly DataView View = new(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x"); + + [Fact] + public async Task A_faulting_inner_connection_is_a_per_item_communication_failure_and_a_caller_cancel_throws() + { + var lease = new DataConnectionDeploymentLease(new Faulting(), CancellationToken.None, DataOperationSets.V1 | DataOperations.HistoryRead, + TimeSpan.FromSeconds(5), 16, 16, 1 << 20, 4, 16, 1 << 20, () => true, () => { }); + var request = new DataHistoryReadRequest(new DataHistoryRawDetails(null, DateTimeOffset.UnixEpoch, 1, false), [new("a", View)], + new DataBudget(TimeSpan.FromSeconds(5), 16, 1 << 20)); + (await lease.ReadHistoryAsync(request, TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x80310000u); + using var cancelled = new CancellationTokenSource(); + await cancelled.CancelAsync(); + await Should.ThrowAsync(() => lease.ReadHistoryAsync(request, cancelled.Token)); + } + + private sealed class Faulting : IDataConnection, IDataHistoryService + { + public DataTarget Target { get; } = new(DataTargetMode.Node, "c", "a"); + public TimeProvider Clock => TimeProvider.System; + public Task> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + throw new InvalidOperationException("No ready authenticated data endpoint."); + } + public Task ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) => Task.CompletedTask; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + Task> IDataReadService.ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task SubscribeAsync(CancellationToken cancellationToken) => throw new NotSupportedException(); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +}