diff --git a/docs/AlarmHistorian.md b/docs/AlarmHistorian.md index 0600c2205..3abe4cfcb 100644 --- a/docs/AlarmHistorian.md +++ b/docs/AlarmHistorian.md @@ -314,6 +314,11 @@ Warning says "HELD by a historian outage", and the readiness check is still **De meter, next to `queue.stalled`) reads 1 only for the outage. The SqlServer writer counts a statement-level refusal as an answer but NOT a login failure / refused connection / pool exhaustion (`SqlServerAlarmHistorianWriter.Answered`, via `IsOutage` — it used `!IsTransient`, which counted those as reachable); QuestDB likewise excludes SQLSTATE class 08/28/53/57. +The Gateway writer (#1096, `GatewayAlarmHistorianWriter.IsGatewayAnswer`) counts a failure as an answer only when it carries a gRPC +status that is not a systemic code AND was not fabricated client-side: a status with a `Status.DebugException` (a connection +reset / HTTP/2 RST_STREAM surfaced as `Internal`/`Unknown`) or a Grpc.Net.Client detail such as `Bad gRPC response. HTTP status code: 5xx` +(a proxy) is not an answer; a genuine gateway `Internal` (historian rejection) / `Unknown` (throwing handler) is. A status-less +exception is never an answer. The `Unimplemented` batch probe still counts (it is a real gateway reply). A writer that does not report reachability keeps the #1034 behaviour (stalled also fires on an outage; `LastError` says which). A node that is not the drain owner is never stalled and promotion restarts the clock. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayAlarmHistorianWriter.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayAlarmHistorianWriter.cs index a0500893f..886faa9cb 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayAlarmHistorianWriter.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayAlarmHistorianWriter.cs @@ -76,10 +76,42 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos /// public DateTime? LastReachableUtc => _reach.LastUtc; - // #1071: any gateway answer (success, or a failure that is not a systemic outage/transport fault) proves it reachable. + // #1071/#1096: only a genuine gateway answer proves it reachable (see IsGatewayAnswer). private void NoteAnswered(Exception ex) { - if (!IsSystemicFailure(ex)) _reach.Touch(); + if (IsGatewayAnswer(ex)) _reach.Touch(); + } + + // Grpc.Net.Client's own client-side status details (it fabricates these when no gateway status came back). + private static readonly string[] TransportDetailPrefixes = + [ + "Bad gRPC response", "Error starting gRPC call", "Error reading next message", "Error sending message", + "Failed to deserialize response message", "Invalid content-type", "Error connecting to subchannel", + ]; + + /// + /// Whether a failed call is evidence that the GATEWAY itself responded (#1096). Needs a gRPC status, and that status + /// must not be (outage / auth / deadline), and must not have been fabricated on the + /// client side. The last matters for Unknown/Internal (and any code): the gateway genuinely returns + /// Internal for a historian-side rejection and ASP.NET Core returns Unknown for a throwing handler, but + /// Grpc.Net.Client ALSO reports Internal/Unknown/Unimplemented for a connection reset mid-call or + /// an HTTP/2 RST_STREAM (it attaches the transport exception as Status.DebugException) and for a non-gRPC reply + /// from a proxy ("Bad gRPC response. HTTP status code: 5xx"). A server-sent status has neither. A failure with no + /// gRPC status at all (a plain client/transport exception) is not an answer either. + /// + internal static bool IsGatewayAnswer(Exception exception) + { + if (IsSystemicFailure(exception)) return false; + for (Exception? e = exception; e is not null; e = e.InnerException) + { + if (e is not RpcException rpc) continue; + if (rpc.Status.DebugException is not null) return false; + var detail = rpc.Status.Detail ?? string.Empty; + foreach (var prefix in TransportDetailPrefixes) + if (detail.StartsWith(prefix, StringComparison.Ordinal)) return false; + return true; + } + return false; } /// Set once the gateway answers SendEvents with Unimplemented: single sends from then on. @@ -100,8 +132,16 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos /// The most single SendEvent RPCs one batch has in flight at once (the fallback path). public const int MaxSendsInFlight = 8; - /// Whether the writer has fallen back to single sends for good (the gateway has no SendEvents) — diagnostic. - internal bool BatchUnsupported => _batchUnsupported; + /// + /// Whether the writer has fallen back to single sends for good (the gateway has no SendEvents). Internal setter + /// (#1096): lets tests start on the single-send path without the Unimplemented probe, which is itself a gateway + /// answer. + /// + internal bool BatchUnsupported + { + get => _batchUnsupported; + set => _batchUnsupported = value; + } /// public async Task> WriteBatchAsync( diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmWriterReachabilityTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmWriterReachabilityTests.cs index 9872deac4..9fcaf4d57 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmWriterReachabilityTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmWriterReachabilityTests.cs @@ -28,9 +28,108 @@ public sealed class GatewayAlarmWriterReachabilityTests /// Puts the writer on the single-send path WITHOUT the Unimplemented probe, which is itself a gateway answer and would /// stamp reachability before the failure under test. /// - private static void UseSingleSends(GatewayAlarmHistorianWriter w) => - typeof(GatewayAlarmHistorianWriter).GetField("_batchUnsupported", - System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.SetValue(w, true); + private static void UseSingleSends(GatewayAlarmHistorianWriter w) => w.BatchUnsupported = true; + + private static Exception WrappedRpc(StatusCode code, string detail, Exception? debug = null) => + new HistorianGatewayException(detail, new RpcException(new Status(code, detail, debug))); + + // #1096: pin every status code. Server-sent codes with no client-side evidence: + [Theory] + [InlineData(StatusCode.InvalidArgument, true)] + [InlineData(StatusCode.FailedPrecondition, true)] + [InlineData(StatusCode.OutOfRange, true)] + [InlineData(StatusCode.NotFound, true)] + [InlineData(StatusCode.AlreadyExists, true)] + [InlineData(StatusCode.Unimplemented, true)] + [InlineData(StatusCode.Internal, true)] + [InlineData(StatusCode.Unknown, true)] + [InlineData(StatusCode.DataLoss, true)] + [InlineData(StatusCode.Unavailable, false)] + [InlineData(StatusCode.DeadlineExceeded, false)] + [InlineData(StatusCode.Cancelled, false)] + [InlineData(StatusCode.ResourceExhausted, false)] + [InlineData(StatusCode.Aborted, false)] + [InlineData(StatusCode.Unauthenticated, false)] + [InlineData(StatusCode.PermissionDenied, false)] + public void Every_server_sent_status_code_is_classified(StatusCode code, bool answered) => + GatewayAlarmHistorianWriter.IsGatewayAnswer(Wrapped(code)).ShouldBe(answered); + + [Theory] + [InlineData(StatusCode.Internal, "Bad gRPC response. HTTP status code: 500")] + [InlineData(StatusCode.Unknown, "Bad gRPC response. HTTP status code: 502")] + [InlineData(StatusCode.Unimplemented, "Bad gRPC response. HTTP status code: 404")] + [InlineData(StatusCode.Internal, "Error starting gRPC call. HttpRequestException: reset")] + [InlineData(StatusCode.Unknown, "Error reading next message. IOException: reset")] + public void A_client_fabricated_status_from_a_proxy_or_reset_is_not_an_answer(StatusCode code, string detail) => + GatewayAlarmHistorianWriter.IsGatewayAnswer(WrappedRpc(code, detail)).ShouldBeFalse(); + + [Theory] + [InlineData(StatusCode.Internal)] + [InlineData(StatusCode.Unknown)] + public void A_status_carrying_a_transport_debug_exception_is_not_an_answer(StatusCode code) => + GatewayAlarmHistorianWriter.IsGatewayAnswer( + WrappedRpc(code, "Received RST_STREAM with error code 2", new IOException("reset"))).ShouldBeFalse(); + + [Fact] + public void A_failure_with_no_grpc_status_is_not_an_answer() + { + GatewayAlarmHistorianWriter.IsGatewayAnswer(new InvalidOperationException("x")).ShouldBeFalse(); + GatewayAlarmHistorianWriter.IsGatewayAnswer(new HistorianGatewayException("x")).ShouldBeFalse(); + } + + [Theory] + [InlineData(StatusCode.Internal)] + [InlineData(StatusCode.Unknown)] + public async Task A_genuine_gateway_Internal_or_Unknown_on_a_single_send_counts_as_answered(StatusCode code) + { + var fake = new FakeHistorianGatewayClient { SendEventThrows = Wrapped(code) }; + using var w = Writer(fake); + UseSingleSends(w); + await w.WriteBatchAsync([Evt()], Ct); + w.LastReachableUtc.ShouldNotBeNull(); + } + + [Fact] + public async Task A_proxy_Internal_on_a_single_send_does_not_count_as_answered() + { + var fake = new FakeHistorianGatewayClient + { + SendEventThrows = WrappedRpc(StatusCode.Internal, "Bad gRPC response. HTTP status code: 500"), + }; + using var w = Writer(fake); + UseSingleSends(w); + await w.WriteBatchAsync([Evt()], Ct); + w.LastReachableUtc.ShouldBeNull(); + } + + [Fact] + public async Task A_proxy_Unknown_on_SendEvents_does_not_count_as_answered() + { + var reset = WrappedRpc(StatusCode.Unknown, "Error starting gRPC call. HttpRequestException: reset"); + var fake = new FakeHistorianGatewayClient + { + SendEventsSource = (_, _) => Task.FromException(reset), + SendEventThrows = reset, + }; + using var w = Writer(fake); + await w.WriteBatchAsync([Evt()], Ct); + w.LastReachableUtc.ShouldBeNull(); + } + + [Fact] + public async Task The_Unimplemented_batch_probe_counts_as_answered_and_flips_to_single_sends() + { + var fake = new FakeHistorianGatewayClient + { + SendEventsSource = (_, _) => Task.FromException(Wrapped(StatusCode.Unimplemented)), + SendEventThrows = Wrapped(StatusCode.Unavailable), // the follow-up single send fails, so only the probe stamps + }; + using var w = Writer(fake); + w.BatchUnsupported.ShouldBeFalse(); + await w.WriteBatchAsync([Evt()], Ct); + w.BatchUnsupported.ShouldBeTrue(); + w.LastReachableUtc.ShouldNotBeNull(); + } private static Exception Wrapped(StatusCode code) => new HistorianGatewayException(code.ToString(), new RpcException(new Status(code, code.ToString())));