diff --git a/docs/AlarmHistorian.md b/docs/AlarmHistorian.md index c6689d5d0..0600c2205 100644 --- a/docs/AlarmHistorian.md +++ b/docs/AlarmHistorian.md @@ -309,6 +309,11 @@ last write attempt the historian *answered* (success or a data-level refusal; a the historian answered within the last 5 minutes ⇒ **`Stalled`** (a stuck head); it has not ⇒ **`HistorianUnreachable`** (rows are merely held; `Stalled` stays false, the `queue.stalled` gauge reads 0, the Warning says "HELD by a historian outage", and the readiness check is still **Degraded** with an outage description). +**#1089:** the AdminUI page (`/alarms-historian`) shows a red **Historian unreachable** badge for the outage and an amber +**Queue stalled** badge for a stuck head (mutually exclusive); the gauge `otopcua.alarm_historian.unreachable` (1/0, same +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. 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.QuestDb/QuestDbAlarmHistorianWriter.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbAlarmHistorianWriter.cs index e67898363..d3974304a 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbAlarmHistorianWriter.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbAlarmHistorianWriter.cs @@ -145,10 +145,22 @@ internal sealed class QuestDbAlarmHistorianWriter : IAlarmHistorianWriter // #1071: a server-side refusal (not a transport/transient fault) proves the historian answered. private bool NoteAnswered(Exception ex) { - if (!QuestDbConnection.IsTransient(ex)) _reach.Touch(); + if (Answered(ex)) _reach.Touch(); return false; } + /// + /// Whether a failed statement proves QuestDB answered (#1089): a server rejection of the statement does; a transient + /// transport fault, or a connection/authentication-level refusal (SQLSTATE class 08 / 28 / 53 / 57) does not. + /// + /// The failure. + /// Whether the server demonstrably answered. + internal static bool Answered(Exception ex) => + !QuestDbConnection.IsTransient(ex) + && !(ex is PostgresException pg && pg.SqlState is { Length: >= 2 } st + && (st.StartsWith("08", StringComparison.Ordinal) || st.StartsWith("28", StringComparison.Ordinal) + || st.StartsWith("53", StringComparison.Ordinal) || st.StartsWith("57", StringComparison.Ordinal))); + /// Classifies a write exception as retryable or a permanent dead-letter failure. /// The exception raised by the write. /// The write outcome the exception maps to. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer/SqlServerAlarmHistorianWriter.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer/SqlServerAlarmHistorianWriter.cs index d00762432..f78455c08 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer/SqlServerAlarmHistorianWriter.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer/SqlServerAlarmHistorianWriter.cs @@ -151,10 +151,20 @@ internal sealed class SqlServerAlarmHistorianWriter : IAlarmHistorianWriter // #1071: a server-side refusal (not a transport/transient fault) proves the historian answered. private bool NoteAnswered(Exception ex) { - if (!SqlHistorianConnection.IsTransient(ex)) _reach.Touch(); + if (Answered(ex)) _reach.Touch(); return false; } + /// + /// Whether a failed statement proves the SQL Server answered (#1089): a statement-level refusal (data error, constraint) + /// does; a transient fault, a timeout or a connection-level failure (login failed, server unreachable, pool exhausted) + /// does not. It used !IsTransient, which counted a login failure or a refused connection as an answer and so + /// reported a dead historian reachable. + /// + /// The failure. + /// Whether the server demonstrably answered. + internal static bool Answered(Exception ex) => !SqlHistorianConnection.IsOutage(ex); + /// Classifies a write failure. Only a data error SQL Server will reject forever dead-letters; anything unknown or non-SQL retries (never lose alarm history). /// The exception raised by the write. /// The write outcome the retry queue should act on. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/AlarmsHistorian.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/AlarmsHistorian.razor index bf71836d1..cf329cd07 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/AlarmsHistorian.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/AlarmsHistorian.razor @@ -52,6 +52,15 @@ else

Drain state

State@_status.DrainState
+ @if (_status.HistorianUnreachable) + { + @* #1089: an outage (the historian itself is not answering; rows are held) - distinct from a stuck queue. *@ +
HealthHistorian unreachable
+ } + else if (_status.Stalled) + { +
HealthQueue stalled
+ }
Last drain@(_status.LastDrainUtc?.ToString("u") ?? "—")
Last success@(_status.LastSuccessUtc?.ToString("u") ?? "—")
@if (!string.IsNullOrWhiteSpace(_status.LastError)) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/AlarmHistorianMetrics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/AlarmHistorianMetrics.cs index 73cb08299..fbb5e8664 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/AlarmHistorianMetrics.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/AlarmHistorianMetrics.cs @@ -13,6 +13,8 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Historian; /// /// otopcua.alarm_historian.queue.stalled — 1 when rows are queued on the draining node and none has been /// delivered or dead-lettered for AlarmHistorian:StallThresholdHours; else 0. Alert on it. +/// otopcua.alarm_historian.unreachable — 1 when the queue is held because the historian is unreachable (#1089, +/// mutually exclusive with queue.stalled). /// otopcua.alarm_historian.queue.depth / .dead_letter_depth — rows waiting / dead-lettered. /// /// @@ -21,6 +23,9 @@ public static class AlarmHistorianMetrics /// Gauge name: 1 while the queue is stalled. public const string StalledGaugeName = "otopcua.alarm_historian.queue.stalled"; + /// Gauge name: 1 while the historian is unreachable and the queue is held (#1089). + public const string UnreachableGaugeName = "otopcua.alarm_historian.unreachable"; + private static volatile IAlarmHistorianSink? _sink; static AlarmHistorianMetrics() @@ -28,6 +33,9 @@ public static class AlarmHistorianMetrics OtOpcUaTelemetry.Meter.CreateObservableGauge( StalledGaugeName, () => Status()?.Stalled == true ? 1 : 0, unit: "{state}", description: "1 when alarm events are queued on the draining node and none was delivered or dead-lettered for AlarmHistorian:StallThresholdHours (a long outage or retry-forever rows at the queue head)."); + OtOpcUaTelemetry.Meter.CreateObservableGauge( + UnreachableGaugeName, () => Status()?.HistorianUnreachable == true ? 1 : 0, unit: "{state}", + description: "1 when the alarm queue has made no progress for AlarmHistorian:StallThresholdHours because the historian itself is unreachable (an outage, not a stuck queue; rows are held). Distinct from queue.stalled."); OtOpcUaTelemetry.Meter.CreateObservableGauge( "otopcua.alarm_historian.queue.depth", () => Status()?.QueueDepth ?? 0L, unit: "{event}", description: "Alarm events waiting in the store-and-forward queue."); 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 new file mode 100644 index 000000000..9872deac4 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmWriterReachabilityTests.cs @@ -0,0 +1,136 @@ +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; + +/// +/// #1089: the Gateway alarm writer stamps only when the gateway +/// actually answered — a success or a data-level refusal — and never for Unavailable / DeadlineExceeded / auth failures. +/// +public sealed class GatewayAlarmWriterReachabilityTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static AlarmHistorianEvent Evt(int i = 0) => 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); + + /// + /// 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 Exception Wrapped(StatusCode code) => + new HistorianGatewayException(code.ToString(), new RpcException(new Status(code, code.ToString()))); + + [Fact] + public void A_fresh_writer_reports_reachability_but_has_not_heard_from_the_gateway() + { + using var w = Writer(new FakeHistorianGatewayClient()); + w.ReportsReachability.ShouldBeTrue(); + w.LastReachableUtc.ShouldBeNull(); + } + + [Fact] + public async Task A_successful_SendEvents_counts_as_answered() + { + var fake = new FakeHistorianGatewayClient { SendEventsSource = (_, _) => Task.FromResult(new SendEventsReply()) }; + using var w = Writer(fake); + await w.WriteBatchAsync([Evt()], Ct); + w.LastReachableUtc.ShouldNotBeNull(); + } + + [Fact] + public async Task A_successful_single_SendEvent_counts_as_answered() + { + var fake = new FakeHistorianGatewayClient(); // SendEvents unset => Unimplemented => singles; SendEventResult succeeds + using var w = Writer(fake); + await w.WriteBatchAsync([Evt()], Ct); + w.LastReachableUtc.ShouldNotBeNull(); + } + + [Theory] + [InlineData(StatusCode.InvalidArgument)] + [InlineData(StatusCode.FailedPrecondition)] + [InlineData(StatusCode.OutOfRange)] + public async Task A_data_level_refusal_of_a_single_event_counts_as_answered(StatusCode code) + { + var fake = new FakeHistorianGatewayClient { SendEventThrows = Wrapped(code) }; + using var w = Writer(fake); + var outcomes = await w.WriteBatchAsync([Evt()], Ct); + outcomes.ShouldBe([HistorianWriteOutcome.PermanentFail]); + w.LastReachableUtc.ShouldNotBeNull(); + } + + [Fact] + public async Task A_data_level_refusal_of_a_batch_counts_as_answered() + { + var fake = new FakeHistorianGatewayClient + { + SendEventsSource = (_, _) => Task.FromException(Wrapped(StatusCode.InvalidArgument)), + }; + using var w = Writer(fake); + await w.WriteBatchAsync([Evt()], Ct); + w.LastReachableUtc.ShouldNotBeNull(); + } + + [Theory] + [InlineData(StatusCode.Unavailable)] + [InlineData(StatusCode.DeadlineExceeded)] + [InlineData(StatusCode.Unauthenticated)] + [InlineData(StatusCode.PermissionDenied)] + public async Task A_systemic_failure_of_SendEvents_does_not_count_as_answered(StatusCode code) + { + var fake = new FakeHistorianGatewayClient + { + SendEventsSource = (_, _) => Task.FromException(Wrapped(code)), + }; + using var w = Writer(fake); + await w.WriteBatchAsync([Evt()], Ct); + w.LastReachableUtc.ShouldBeNull(); + } + + [Theory] + [InlineData(StatusCode.Unavailable)] + [InlineData(StatusCode.DeadlineExceeded)] + [InlineData(StatusCode.Unauthenticated)] + [InlineData(StatusCode.PermissionDenied)] + public async Task A_systemic_failure_of_a_single_SendEvent_does_not_count_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.ShouldBeNull(); + } + + [Fact] + public async Task Typed_auth_and_unavailable_client_exceptions_do_not_count_as_answered() + { + foreach (Exception ex in new Exception[] + { + new HistorianGatewayUnavailableException("down"), + new HistorianGatewayAuthenticationException("bad key"), + new HistorianGatewayAuthorizationException("no scope"), + }) + { + var fake = new FakeHistorianGatewayClient { SendEventThrows = ex }; + using var w = Writer(fake); + UseSingleSends(w); + await w.WriteBatchAsync([Evt()], Ct); + w.LastReachableUtc.ShouldBeNull(ex.GetType().Name); + } + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests/AlarmWriterTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests/AlarmWriterTests.cs index 506bac2d9..509ac9e03 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests/AlarmWriterTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests/AlarmWriterTests.cs @@ -71,6 +71,21 @@ public sealed class AlarmWriterTests(QuestDbFixture fx) (await CountAsync(c)).ShouldBe(1200, "DEDUP UPSERT KEYS(ts, event_id) converges a redelivered batch"); } + // #1089: a write the server answered stamps reachability; a row dropped before any send does not. + [Fact] + public async Task A_successful_write_stamps_reachability_and_an_unsendable_event_does_not() + { + fx.SkipIfUnavailable(); + var (w, _) = Make(); + w.LastReachableUtc.ShouldBeNull(); + var old = new AlarmHistorianEvent("alarm-1", "Plant/Line/Eq", "HiTemp", "LimitAlarm", AlarmSeverity.High, + "old", "msg", "user", null, new DateTime(1969, 12, 31, 0, 0, 0, DateTimeKind.Utc)); + (await w.WriteBatchAsync([old], CancellationToken.None)).ShouldBe([HistorianWriteOutcome.PermanentFail]); + w.LastReachableUtc.ShouldBeNull("nothing was sent"); + (await w.WriteBatchAsync([Ev()], CancellationToken.None)).ShouldBe([HistorianWriteOutcome.Ack]); + w.LastReachableUtc.ShouldNotBeNull(); + } + [Fact] public async Task Event_round_trips_and_a_repeat_is_one_row_with_every_write_Ack() { diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.Tests/QuestDbAlarmWriterReachabilityTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.Tests/QuestDbAlarmWriterReachabilityTests.cs new file mode 100644 index 000000000..dfab56fb2 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.Tests/QuestDbAlarmWriterReachabilityTests.cs @@ -0,0 +1,41 @@ +using System.Net.Sockets; +using Npgsql; +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.Tests; + +/// +/// #1089: the QuestDB alarm writer's reachability touch point on a failed statement +/// (): a server-side refusal proves QuestDB answered, a transport +/// fault or a connection/auth-level refusal does not. +/// +public sealed class QuestDbAlarmWriterReachabilityTests +{ + private static PostgresException Pg(string sqlState, string message = "rejected") => + new(message, "ERROR", "ERROR", sqlState); + + [Theory] + [InlineData("00000")] // QuestDB reports every server error with SQLSTATE 00000 + [InlineData("22001")] // data exception + [InlineData("23505")] // integrity + public void A_statement_level_server_rejection_counts_as_answered(string sqlState) => + QuestDbAlarmHistorianWriter.Answered(Pg(sqlState)).ShouldBeTrue(); + + [Theory] + [InlineData("28P01")] // invalid password + [InlineData("28000")] // invalid authorization + [InlineData("08006")] // connection failure + [InlineData("53300")] // too many connections + [InlineData("57P03")] // cannot connect now + public void An_auth_or_connection_level_refusal_does_not_count_as_answered(string sqlState) => + QuestDbAlarmHistorianWriter.Answered(Pg(sqlState)).ShouldBeFalse(); + + [Fact] + public void Transport_faults_and_timeouts_do_not_count_as_answered() + { + QuestDbAlarmHistorianWriter.Answered(new NpgsqlException("down", new SocketException())).ShouldBeFalse(); + QuestDbAlarmHistorianWriter.Answered(new TimeoutException()).ShouldBeFalse(); + QuestDbAlarmHistorianWriter.Answered(new IOException("reset")).ShouldBeFalse(); + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer.IntegrationTests/AlarmWriterTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer.IntegrationTests/AlarmWriterTests.cs index 36f203527..6ddeff52f 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer.IntegrationTests/AlarmWriterTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer.IntegrationTests/AlarmWriterTests.cs @@ -63,6 +63,30 @@ public sealed class AlarmWriterTests(SqlHistorianFixture fx) r.ShouldBe([HistorianWriteOutcome.Ack, HistorianWriteOutcome.PermanentFail, HistorianWriteOutcome.Ack]); } + // #1089: reachability is stamped by an ANSWER (a write, or a server-side data refusal), never by an outage. + [Fact] + public async Task A_successful_write_and_a_data_refusal_both_stamp_reachability() + { + fx.SkipIfUnavailable(); + var (w, _) = Make(); + w.LastReachableUtc.ShouldBeNull(); + (await w.WriteBatchAsync([Ev()], CancellationToken.None)).ShouldBe([HistorianWriteOutcome.Ack]); + w.LastReachableUtc.ShouldNotBeNull(); + + var (refused, _) = Make(); + (await refused.WriteBatchAsync([Ev(type: new string('t', 101))], CancellationToken.None)) + .ShouldBe([HistorianWriteOutcome.PermanentFail]); + refused.LastReachableUtc.ShouldNotBeNull("a 8152 truncation is the server answering"); + } + + [Fact] + public async Task An_unreachable_server_does_not_stamp_reachability() + { + var (w, _) = Make("Server=127.0.0.1,1;User Id=x;Password=x;Encrypt=False;Connect Timeout=2"); + (await w.WriteBatchAsync([Ev()], CancellationToken.None)).ShouldBe([HistorianWriteOutcome.RetryPlease]); + w.LastReachableUtc.ShouldBeNull(); + } + [Fact] public async Task An_event_reads_back_with_its_type_name_condition_name_and_alarm_id() { diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer.Tests/SqlOutageClassificationTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer.Tests/SqlOutageClassificationTests.cs index fdb8f46da..738fe1d19 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer.Tests/SqlOutageClassificationTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer.Tests/SqlOutageClassificationTests.cs @@ -49,6 +49,30 @@ public sealed class SqlOutageClassificationTests public void Positive_control_an_unrelated_InvalidOperationException_is_not_an_outage() => SqlHistorianConnection.IsOutage(new InvalidOperationException("unexpected")).ShouldBeFalse(); + // #1089: the writer's reachability touch point (SqlServerAlarmHistorianWriter.Answered) on a failed statement. + [Theory] + [InlineData(8152)] // data error: the server refused the row, so it answered + [InlineData(515)] // null into NOT NULL + [InlineData(547)] // constraint + public void A_statement_level_refusal_counts_as_the_historian_answering(int number) => + SqlServerAlarmHistorianWriter.Answered(SqlError(number, errorClass: 16)).ShouldBeTrue(); + + [Theory] + [InlineData(18456)] // login failed (auth) + [InlineData(53)] // network path not found + [InlineData(40)] // could not open a connection + [InlineData(10061)] // connection refused + public void An_outage_or_auth_failure_does_not_count_as_answered(int number) => + SqlServerAlarmHistorianWriter.Answered(SqlError(number, errorClass: 14)).ShouldBeFalse(); + + [Fact] + public void A_timeout_or_exhausted_pool_does_not_count_as_answered() + { + SqlServerAlarmHistorianWriter.Answered(new TimeoutException()).ShouldBeFalse(); + SqlServerAlarmHistorianWriter.Answered(new InvalidOperationException( + "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool.")).ShouldBeFalse(); + } + private const BindingFlags NonPublic = BindingFlags.NonPublic | BindingFlags.Instance; /// A real (internal factory, by reflection) with one error. diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/AlarmsHistorianPageTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/AlarmsHistorianPageTests.cs new file mode 100644 index 000000000..ea179b00c --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/AlarmsHistorianPageTests.cs @@ -0,0 +1,66 @@ +using Akka.Actor; +using Akka.Hosting; +using Bunit; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Pages; +using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian; +using ZB.MOM.WW.OtOpcUa.Runtime; +using ZB.MOM.WW.OtOpcUa.Runtime.Historian; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Pages; + +/// #1089: /alarms-historian shows a historian outage with its own badge, distinct from "stalled". +[Trait("Category", "Unit")] +public sealed class AlarmsHistorianPageTests : BunitContext +{ + private sealed class StatusActor : ReceiveActor + { + public StatusActor(HistorianSinkStatus status) => Receive(_ => Sender.Tell(status)); + } + + private sealed class Required(IActorRef actor) : IRequiredActor + { + public IActorRef ActorRef { get; } = actor; + public Task GetAsync(CancellationToken cancellationToken = default) => Task.FromResult(ActorRef); + } + + private static HistorianSinkStatus Status(bool stalled, bool unreachable) => + new(5, 0, null, null, "Historian unavailable", HistorianDrainState.BackingOff, Stalled: stalled, HistorianUnreachable: unreachable); + + private IRenderedComponent RenderPage(ActorSystem sys, HistorianSinkStatus status) + { + JSInterop.Mode = JSRuntimeMode.Loose; + var actor = sys.ActorOf(Props.Create(() => new StatusActor(status))); + Services.AddSingleton>(new Required(actor)); + return Render(); + } + + [Fact] + public void An_unreachable_historian_shows_its_own_badge_and_not_the_stalled_one() + { + using var sys = ActorSystem.Create("hist-ui-1"); + var cut = RenderPage(sys, Status(stalled: false, unreachable: true)); + cut.WaitForAssertion(() => cut.Find("[data-testid=historian-unreachable]").TextContent.ShouldContain("unreachable")); + cut.FindAll("[data-testid=queue-stalled]").ShouldBeEmpty(); + } + + [Fact] + public void A_stalled_queue_shows_the_stalled_badge_and_not_the_unreachable_one() + { + using var sys = ActorSystem.Create("hist-ui-2"); + var cut = RenderPage(sys, Status(stalled: true, unreachable: false)); + cut.WaitForAssertion(() => cut.Find("[data-testid=queue-stalled]").TextContent.ShouldContain("stalled")); + cut.FindAll("[data-testid=historian-unreachable]").ShouldBeEmpty(); + } + + [Fact] + public void A_healthy_sink_shows_neither_badge() + { + using var sys = ActorSystem.Create("hist-ui-3"); + var cut = RenderPage(sys, Status(stalled: false, unreachable: false)); + cut.WaitForAssertion(() => cut.Find(".metric-card").TextContent.ShouldContain("Depth")); + cut.FindAll("[data-testid=queue-stalled],[data-testid=historian-unreachable]").ShouldBeEmpty(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/AlarmHistorianMetricsTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/AlarmHistorianMetricsTests.cs index c04109c2a..39e6c5559 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/AlarmHistorianMetricsTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/AlarmHistorianMetricsTests.cs @@ -24,23 +24,37 @@ public sealed class AlarmHistorianMetricsTests Observe().ShouldBe(0); } - private static int Observe() + private static int Observe(string name = AlarmHistorianMetrics.StalledGaugeName) { var seen = new List(); using var listener = new MeterListener { InstrumentPublished = (inst, l) => { - if (ReferenceEquals(inst.Meter, OtOpcUaTelemetry.Meter) && inst.Name == AlarmHistorianMetrics.StalledGaugeName) + if (ReferenceEquals(inst.Meter, OtOpcUaTelemetry.Meter) && inst.Name == name) l.EnableMeasurementEvents(inst); }, }; - listener.SetMeasurementEventCallback((inst, v, _, _) => { if (inst.Name == AlarmHistorianMetrics.StalledGaugeName) seen.Add(v); }); + listener.SetMeasurementEventCallback((inst, v, _, _) => { if (inst.Name == name) seen.Add(v); }); listener.Start(); listener.RecordObservableInstruments(); return seen.Single(); } + [Fact] + public void The_unreachable_gauge_reads_1_only_for_an_outage_and_is_distinct_from_stalled() + { + var sink = new SwitchSink(); + AlarmHistorianMetrics.Bind(sink); + + Observe(AlarmHistorianMetrics.UnreachableGaugeName).ShouldBe(0); + sink.Unreachable = true; + Observe(AlarmHistorianMetrics.UnreachableGaugeName).ShouldBe(1); + Observe().ShouldBe(0); // an outage is not "stalled" + sink.Unreachable = false; + Observe(AlarmHistorianMetrics.UnreachableGaugeName).ShouldBe(0); + } + [Fact] public void Options_default_to_a_two_hour_stall_threshold_and_no_revival_and_zero_disables() { @@ -54,7 +68,8 @@ public sealed class AlarmHistorianMetricsTests private sealed class SwitchSink : IAlarmHistorianSink { public volatile bool Stalled; + public volatile bool Unreachable; public Task EnqueueAsync(AlarmHistorianEvent evt, CancellationToken cancellationToken) => Task.CompletedTask; - public HistorianSinkStatus GetStatus() => new(1, 0, null, null, null, HistorianDrainState.BackingOff, Stalled: Stalled); + public HistorianSinkStatus GetStatus() => new(1, 0, null, null, null, HistorianDrainState.BackingOff, Stalled: Stalled, HistorianUnreachable: Unreachable); } }