using Grpc.Core; using Microsoft.Extensions.Logging.Abstractions; using Shouldly; using Xunit; using ZB.MOM.WW.HistorianGateway.Client; using ZB.MOM.WW.HistorianGateway.Contracts.Grpc; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian; namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests; /// /// G-8 (#976): a transient gateway condition must never dead-letter alarm history. The gateway answers a server-side /// cancellation (shutdown / internal timeout) with Cancelled and an unmapped server fault with Unknown; /// a dropped channel surfaces as a plain transport exception. Only codes that prove the EVENT is bad dead-letter. /// public sealed class GatewayAlarmWriterTransientClassificationTests { private static CancellationToken Ct => TestContext.Current.CancellationToken; private static AlarmHistorianEvent Evt(int i) => new( $"alarm-{i}", "Area/Pump", "N", "LimitAlarm", AlarmSeverity.High, "Activated", $"m{i}", "u", null, new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(i)); private static GatewayAlarmHistorianWriter Writer(FakeHistorianGatewayClient fake) => new(fake, NullLogger.Instance); /// The published client wraps every code it has no typed exception for in the base type, inner RpcException. private static Exception Wrapped(StatusCode code) => new HistorianGatewayException(code.ToString(), new RpcException(new Status(code, code.ToString()))); public static TheoryData TransientCodes => [ StatusCode.Cancelled, StatusCode.Unknown, StatusCode.DataLoss, StatusCode.Unavailable, StatusCode.DeadlineExceeded, StatusCode.ResourceExhausted, StatusCode.Aborted, StatusCode.Internal, ]; /// The codes that are a known outage of the whole path: a batch failing with one is never isolated. public static TheoryData SystemicCodes => [ StatusCode.Cancelled, StatusCode.Unavailable, StatusCode.DeadlineExceeded, StatusCode.ResourceExhausted, StatusCode.Aborted, StatusCode.Unauthenticated, StatusCode.PermissionDenied, ]; /// Retryable but NOT a known outage — may be one event's fault (#976 review): the chunk is isolated per event. public static TheoryData UnrecognisedCodes => [StatusCode.Unknown, StatusCode.DataLoss, StatusCode.Internal]; [Theory] [MemberData(nameof(SystemicCodes))] public async Task A_systemic_code_from_SendEvents_retries_every_event_and_fans_out_nothing(StatusCode code) { var fake = new FakeHistorianGatewayClient { SendEventsSource = (_, _) => Task.FromException(Wrapped(code)), }; using var writer = Writer(fake); var outcomes = await writer.WriteBatchAsync(Enumerable.Range(0, 5).Select(Evt).ToList(), Ct); outcomes.ShouldAllBe(o => o == HistorianWriteOutcome.RetryPlease); fake.SendEventCallCount.ShouldBe(0, "a systemic fault must not be re-sent event by event"); } [Theory] [MemberData(nameof(TransientCodes))] public async Task A_transient_code_from_SendEvent_retries_the_event(StatusCode code) { var fake = new FakeHistorianGatewayClient { SendEventThrows = Wrapped(code) }; // SendEvents unset ⇒ Unimplemented ⇒ singles using var writer = Writer(fake); var outcomes = await writer.WriteBatchAsync(Enumerable.Range(0, 3).Select(Evt).ToList(), Ct); outcomes.ShouldAllBe(o => o == HistorianWriteOutcome.RetryPlease); fake.SendEventCallCount.ShouldBe(3); } [Theory] [MemberData(nameof(UnrecognisedCodes))] public async Task An_unrecognised_code_that_every_single_send_repeats_retries_all_and_stops_after_one_chunk(StatusCode code) { // An outage of a kind the writer cannot recognise: the batch AND every single send fail the same way. var fake = new FakeHistorianGatewayClient { SendEventsSource = (_, _) => Task.FromException(Wrapped(code)), SendEventThrows = Wrapped(code), }; using var writer = Writer(fake); var size = GatewayAlarmHistorianWriter.MaxEventsPerBatch; var outcomes = await writer.WriteBatchAsync(Enumerable.Range(0, size + 5).Select(Evt).ToList(), Ct); outcomes.ShouldAllBe(o => o == HistorianWriteOutcome.RetryPlease, "nothing dead-letters on what may be an outage"); fake.SendEventsCalls.Count.ShouldBe(1, "no single Ack'd, so it was not one event: the next chunk is not sent"); fake.SendEventCallCount.ShouldBe(size, "the fan-out is bounded to the one isolated chunk"); } public static TheoryData TransportFaults => [ new IOException("connection reset"), new HttpRequestException("no route to host"), new ObjectDisposedException("GrpcChannel"), new TaskCanceledException("an internal timeout — not the caller's token"), new HistorianGatewayException("wrapped transport fault", new IOException("connection reset")), new HistorianGatewayUnavailableException("down"), ]; /// Retryable, status-less and not a transport fault: isolated on the batch path (#976 review). public static TheoryData UnrecognisedFaults => [ new HistorianGatewayException("no inner status"), new InvalidOperationException("unexpected"), ]; [Theory] [MemberData(nameof(UnrecognisedFaults))] public async Task An_unrecognised_non_RPC_fault_retries_and_is_isolated_on_the_batch_path(Exception fault) { var fake = new FakeHistorianGatewayClient { SendEventsSource = (_, _) => Task.FromException(fault), SendEventThrows = fault, }; using var writer = Writer(fake); (await writer.WriteBatchAsync(Enumerable.Range(0, 4).Select(Evt).ToList(), Ct)) .ShouldAllBe(o => o == HistorianWriteOutcome.RetryPlease); fake.SendEventCallCount.ShouldBe(4); } [Theory] [MemberData(nameof(TransportFaults))] public async Task A_non_RPC_transport_fault_retries_on_both_paths(Exception fault) { var batchFake = new FakeHistorianGatewayClient { SendEventsSource = (_, _) => Task.FromException(fault) }; using (var writer = Writer(batchFake)) { (await writer.WriteBatchAsync(Enumerable.Range(0, 4).Select(Evt).ToList(), Ct)) .ShouldAllBe(o => o == HistorianWriteOutcome.RetryPlease); batchFake.SendEventCallCount.ShouldBe(0); } var singleFake = new FakeHistorianGatewayClient { SendEventThrows = fault }; using (var writer = Writer(singleFake)) { (await writer.WriteBatchAsync(Enumerable.Range(0, 2).Select(Evt).ToList(), Ct)) .ShouldAllBe(o => o == HistorianWriteOutcome.RetryPlease); } } [Theory] [InlineData(StatusCode.InvalidArgument)] [InlineData(StatusCode.FailedPrecondition)] [InlineData(StatusCode.OutOfRange)] [InlineData(StatusCode.NotFound)] [InlineData(StatusCode.AlreadyExists)] public async Task Positive_control_a_code_that_proves_the_event_bad_still_dead_letters(StatusCode code) { var fake = new FakeHistorianGatewayClient { SendEventThrows = Wrapped(code) }; using var writer = Writer(fake); (await writer.WriteBatchAsync([Evt(0)], Ct)).Single().ShouldBe(HistorianWriteOutcome.PermanentFail); } [Fact] public async Task Positive_control_an_event_that_cannot_be_mapped_dead_letters_without_an_RPC_on_both_paths() { var poison = Evt(1) with { DeliveryId = Guid.Empty }; var batchFake = new FakeHistorianGatewayClient { SendEventsSource = (events, _) => { var reply = new SendEventsReply(); foreach (var e in events) reply.Results.Add(new EventWriteResult { Id = e.Id, Success = true }); return Task.FromResult(reply); }, }; using (var writer = Writer(batchFake)) { (await writer.WriteBatchAsync([Evt(0), poison, Evt(2)], Ct)).ShouldBe( [HistorianWriteOutcome.Ack, HistorianWriteOutcome.PermanentFail, HistorianWriteOutcome.Ack]); batchFake.SendEventsCalls.Single().Count.ShouldBe(2); } var singleFake = new FakeHistorianGatewayClient(); // SendEvents ⇒ Unimplemented ⇒ singles using (var writer = Writer(singleFake)) { (await writer.WriteBatchAsync([Evt(0)], Ct)).Single().ShouldBe(HistorianWriteOutcome.Ack); writer.BatchUnsupported.ShouldBeTrue("the single-send path is what the next write exercises"); (await writer.WriteBatchAsync([poison], Ct)).Single().ShouldBe(HistorianWriteOutcome.PermanentFail); singleFake.SendEventCallCount.ShouldBe(1, "the unmappable event is never sent"); } } }