Merge historian follow-up (#1089): HistorianUnreachable on /alarms-historian + otopcua.alarm_historian.unreachable gauge; per-writer reachability tests; SqlServer writer no longer counts login/connection failures as answered
This commit is contained in:
+136
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// #1089: the Gateway alarm writer stamps <see cref="IAlarmHistorianWriter.LastReachableUtc"/> only when the gateway
|
||||
/// actually answered — a success or a data-level refusal — and never for Unavailable / DeadlineExceeded / auth failures.
|
||||
/// </summary>
|
||||
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<GatewayAlarmHistorianWriter>.Instance);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<SendEventsReply>(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<SendEventsReply>(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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
@@ -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()
|
||||
{
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
using System.Net.Sockets;
|
||||
using Npgsql;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// #1089: the QuestDB alarm writer's reachability touch point on a failed statement
|
||||
/// (<see cref="QuestDbAlarmHistorianWriter.Answered"/>): a server-side refusal proves QuestDB answered, a transport
|
||||
/// fault or a connection/auth-level refusal does not.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
+24
@@ -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()
|
||||
{
|
||||
|
||||
+24
@@ -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;
|
||||
|
||||
/// <summary>A real <see cref="SqlException"/> (internal factory, by reflection) with one error.</summary>
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>#1089: <c>/alarms-historian</c> shows a historian outage with its own badge, distinct from "stalled".</summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class AlarmsHistorianPageTests : BunitContext
|
||||
{
|
||||
private sealed class StatusActor : ReceiveActor
|
||||
{
|
||||
public StatusActor(HistorianSinkStatus status) => Receive<HistorianAdapterActor.GetStatus>(_ => Sender.Tell(status));
|
||||
}
|
||||
|
||||
private sealed class Required(IActorRef actor) : IRequiredActor<HistorianAdapterActorKey>
|
||||
{
|
||||
public IActorRef ActorRef { get; } = actor;
|
||||
public Task<IActorRef> 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<AlarmsHistorian> RenderPage(ActorSystem sys, HistorianSinkStatus status)
|
||||
{
|
||||
JSInterop.Mode = JSRuntimeMode.Loose;
|
||||
var actor = sys.ActorOf(Props.Create(() => new StatusActor(status)));
|
||||
Services.AddSingleton<IRequiredActor<HistorianAdapterActorKey>>(new Required(actor));
|
||||
return Render<AlarmsHistorian>();
|
||||
}
|
||||
|
||||
[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();
|
||||
}
|
||||
}
|
||||
+19
-4
@@ -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<int>();
|
||||
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<int>((inst, v, _, _) => { if (inst.Name == AlarmHistorianMetrics.StalledGaugeName) seen.Add(v); });
|
||||
listener.SetMeasurementEventCallback<int>((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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user