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:
Joseph Doherty
2026-12-04 14:34:06 -05:00
12 changed files with 371 additions and 6 deletions
@@ -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);
}
}
}
@@ -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()
{
@@ -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();
}
}
@@ -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()
{
@@ -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>