From 28de03783ffa47e01b196d596e99e2d35e6b1d55 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Mon, 23 Nov 2026 23:20:53 -0500 Subject: [PATCH] fix(grpc-data): H2 review2-7d/e - caller cancel is OperationCanceledException; abandoned assembly releases chunk tokens A caller cancel during a history call surfaced as RpcException(Cancelled); it now throws OperationCanceledException. When an assembly is abandoned (timeout, communication failure, unsupported, cancel) after a follow-up, the origin chunk tokens it carried are released best effort. --- .../GrpcDataConnection.History.cs | 17 +++++++++- .../GrpcDataHistoryClientTests.cs | 32 ++++++++++++++++++- 2 files changed, 47 insertions(+), 2 deletions(-) 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 1612870ae..71971f68c 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 @@ -158,8 +158,15 @@ public sealed partial class GrpcDataConnection : IDataHistoryService Headers(selected.Channel, RequestedFeatures(selected.Capabilities)), DateTime.UtcNow + deadline, linked.Token)) .ResponseAsync.ConfigureAwait(false); } + catch (Exception ex) when (cancellationToken.IsCancellationRequested && ex is RpcException or OperationCanceledException) + { + // A caller cancel is never an outcome: surface it as cancellation, and let go of held chunk tokens. + if (!first) ReleaseChunkTokens(selected, current); + throw new OperationCanceledException("History read cancelled by the caller.", ex, cancellationToken); + } catch (RpcException ex) when (ex.StatusCode is StatusCode.FailedPrecondition or StatusCode.Unimplemented) { + if (!first) ReleaseChunkTokens(selected, current); foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadHistoryOperationUnsupported, [], null); break; } @@ -167,15 +174,17 @@ public sealed partial class GrpcDataConnection : IDataHistoryService { // 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. + if (!first) ReleaseChunkTokens(selected, current); 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) + catch (RpcException ex) { RecordFailure(ex); + if (!first) ReleaseChunkTokens(selected, current); // the origin still holds their remainders foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadNoCommunication, [], null); break; } @@ -261,6 +270,12 @@ public sealed partial class GrpcDataConnection : IDataHistoryService } } + /// Best effort: a follow-up's items carry origin CHUNK tokens; release them when the assembly is abandoned. + private void ReleaseChunkTokens(Selected selected, IEnumerable items) + { + foreach (var item in items) _ = ReleaseOnEndpointAsync(selected, item.Continuation); + } + private async Task ReleaseOnEndpointAsync(Selected selected, byte[]? token) { if (token is null) return; 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 f12c1703a..a246ccf00 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 @@ -184,6 +184,26 @@ public sealed class GrpcDataHistoryClientTests a.Headers.Count.ShouldBe(probes, "backing off: no new probe"); } + [Fact] + public async Task A_caller_cancel_during_the_call_surfaces_as_OperationCanceledException() + { + var a = new Endpoint("a") { Delay = TimeSpan.FromSeconds(30) }; + await using var connection = Connect([a]); + using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(200)); + await Should.ThrowAsync(() => connection.ReadHistoryAsync(Request(), cancel.Token)); + } + + [Fact] + public async Task A_failure_mid_assembly_releases_the_origin_chunk_tokens_it_holds() + { + var a = new Endpoint("a") { Chunks = 3, FailAfterFirst = Grpc.Core.StatusCode.Internal }; + await using var connection = Connect([a]); + (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x80310000u); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (a.Released.Count == 0 && DateTime.UtcNow < deadline) await Task.Delay(20, TestContext.Current.CancellationToken); + a.Released.ShouldContain(t => t.SequenceEqual(new byte[] { 7, 7 }), "the chunk token the failed follow-up carried is released"); + } + private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? historyTimeout = null) { var manager = new DataConnectionManager("consumer", 1); @@ -203,6 +223,10 @@ public sealed class GrpcDataHistoryClientTests public bool Ready { get; set; } = true; public bool Granted { get; set; } = true; public bool Malformed { get; set; } + /// Delay before answering a HistoryRead (honours the request's token). + public TimeSpan? Delay { get; set; } + /// Fail every HistoryRead after the first with this status. + public Grpc.Core.StatusCode? FailAfterFirst { get; set; } public int Chunks { get; init; } = 1; public byte[]? PageToken { get; init; } public int HistoryCalls; @@ -232,13 +256,19 @@ public sealed class GrpcDataHistoryClientTests } else { - Interlocked.Increment(ref HistoryCalls); + var call = Interlocked.Increment(ref HistoryCalls); if (Fail is { } fail) return Status(fail); + if (Delay is { } delay) await Task.Delay(delay, token); 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 && call > 1 && FailAfterFirst is { } later) + { + LastContinuations = wire.Items.Where(x => x.HasContinuation).Select(x => x.Continuation.ToByteArray()).ToList(); + return Status(later); + } if (wire.ReleaseContinuations) { foreach (var item in wire.Items) Released.Add(item.Continuation.ToByteArray());