using System.Net;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.HistorianGateway.Contracts.Grpc;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Runtime.Historian;
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests;
///
/// lmxopcua#900 on the wire: an in-process gRPC gateway answers ReadAggregate the way a HistorianGateway at or
/// after historiangw#135 (a220ec0) does when AVEVA refuses the retrieval mode for the tag —
/// FailedPrecondition, detail HistorianAggregateNotSupportedException, and a google.rpc.Status holding a
/// google.rpc.ErrorInfo (reason AGGREGATE_NOT_SUPPORTED_FOR_TAG, domain historian_gateway.v1, metadata
/// retrieval_mode + native_error_code) in grpc-status-details-bin (shape copied from the gateway's
/// HistorianRpcFaults.ToRpcException). Read through the PUBLISHED Client 1.1.0 (via the production adapter), so this
/// also pins that 1.1.0 surfaces the trailer as the typed HistorianGatewayException.ErrorReason /
/// ErrorDomain / StatusCode that GatewayErrorReasons reads. Controls: every other shape keeps today's handling
/// (rethrown, counted as a backend failure).
///
public sealed class GatewayAggregateNotSupportedWireTests
{
private static readonly DateTime S0 = new(2026, 11, 13, 12, 0, 0, DateTimeKind.Utc);
private static CancellationToken Ct => TestContext.Current.CancellationToken;
[Theory]
[InlineData(HistoryAggregateType.TimeAverage, RetrievalMode.TimeWeightedAverage)]
[InlineData(HistoryAggregateType.Total, RetrievalMode.Integral)]
public async Task The_gateways_aggregate_refusal_is_BadAggregateNotSupported_and_no_health_failure(
HistoryAggregateType aggregate, RetrievalMode expectedMode)
{
var read = new ReadService { Fault = Refusal };
await using var server = await StartServerAsync(read);
var (adapter, ds) = Create(server.Port);
using var _ = adapter;
var ex = await Should.ThrowAsync(() =>
ds.ReadProcessedAsync("SysPulse", S0, S0.AddMinutes(4), TimeSpan.FromMinutes(2), aggregate, Ct));
ex.Aggregate.ShouldBe(aggregate);
read.Modes.ShouldBe([expectedMode], "the refusal came from the gateway, not up front");
var health = ds.GetHealthSnapshot();
health.TotalFailures.ShouldBe(0, "a tag that cannot serve the aggregate is configuration, not a backend failure");
health.ConsecutiveFailures.ShouldBe(0);
health.LastError.ShouldBeNull();
}
public static TheoryData OrdinaryFailures() =>
[
"internal", // an older gateway / a genuine historian fault: Internal, no ErrorInfo
"failed-precondition-bare", // FailedPrecondition without ErrorInfo (e.g. a historian-side one passed through)
"failed-precondition-other", // FailedPrecondition with another reason
"failed-precondition-domain", // the reason string, but not the gateway's domain
"internal-with-reason", // the reason on a status that is not FailedPrecondition
];
[Theory]
[MemberData(nameof(OrdinaryFailures))]
public async Task Every_other_failure_shape_keeps_todays_handling_and_counts(string shape)
{
var read = new ReadService
{
Fault = shape switch
{
"internal" => () => new RpcException(new Status(StatusCode.Internal, "HistorianServerOperationException")),
"failed-precondition-bare" => () => new RpcException(new Status(StatusCode.FailedPrecondition, "HistorianServerRejectionException")),
"failed-precondition-other" => () => WithErrorInfo(StatusCode.FailedPrecondition, "LIVE_WRITES_DISABLED", "historian_gateway.v1"),
"failed-precondition-domain" => () => WithErrorInfo(StatusCode.FailedPrecondition, "AGGREGATE_NOT_SUPPORTED_FOR_TAG", "example.com"),
"internal-with-reason" => () => WithErrorInfo(StatusCode.Internal, "AGGREGATE_NOT_SUPPORTED_FOR_TAG", "historian_gateway.v1"),
_ => throw new ArgumentOutOfRangeException(nameof(shape)),
},
};
await using var server = await StartServerAsync(read);
var (adapter, ds) = Create(server.Port);
using var _ = adapter;
var ex = await Should.ThrowAsync(() =>
ds.ReadProcessedAsync("SysPulse", S0, S0.AddMinutes(4), TimeSpan.FromMinutes(2), HistoryAggregateType.TimeAverage, Ct));
ex.ShouldNotBeOfType();
ex.ShouldNotBeOfType("a refusal is not a transport failure");
ds.GetHealthSnapshot().TotalFailures.ShouldBe(1, $"{shape} is a backend failure, as before #900");
}
[Fact]
public async Task Positive_control_a_served_aggregate_succeeds_over_the_same_server()
{
var read = new ReadService();
await using var server = await StartServerAsync(read);
var (adapter, ds) = Create(server.Port);
using var _ = adapter;
var result = await ds.ReadProcessedAsync("SysTimeSec", S0, S0.AddMinutes(4), TimeSpan.FromMinutes(2),
HistoryAggregateType.TimeAverage, Ct);
result.Samples.Count.ShouldBe(2);
ds.GetHealthSnapshot().TotalFailures.ShouldBe(0);
ds.GetHealthSnapshot().TotalSuccesses.ShouldBeGreaterThan(0);
}
/// What a gateway at or after historiangw#135 sends (HistorianRpcFaults.ToRpcException).
private static RpcException Refusal() => new(
new Status(StatusCode.FailedPrecondition, "HistorianAggregateNotSupportedException"),
new Metadata
{
{
"grpc-status-details-bin",
new Google.Rpc.Status
{
Code = (int)StatusCode.FailedPrecondition,
Message = "HistorianAggregateNotSupportedException",
Details =
{
Any.Pack(new Google.Rpc.ErrorInfo
{
Reason = "AGGREGATE_NOT_SUPPORTED_FOR_TAG",
Domain = "historian_gateway.v1",
Metadata = { ["retrieval_mode"] = "RETRIEVAL_MODE_TIME_WEIGHTED_AVERAGE", ["native_error_code"] = "85" },
}),
},
}.ToByteArray()
},
});
private static RpcException WithErrorInfo(StatusCode code, string reason, string domain) => new(
new Status(code, "HistorianServerRejectionException"),
new Metadata
{
{
"grpc-status-details-bin",
new Google.Rpc.Status
{
Code = (int)code,
Message = "HistorianServerRejectionException",
Details = { Any.Pack(new Google.Rpc.ErrorInfo { Reason = reason, Domain = domain }) },
}.ToByteArray()
},
});
private static (HistorianGatewayClientAdapter Adapter, GatewayHistorianDataSource Ds) Create(int port)
{
var adapter = HistorianGatewayClientAdapter.Create(
new ServerHistorianOptions { Enabled = true, Endpoint = $"http://127.0.0.1:{port}", ApiKey = "histgw_test_key", UseTls = false },
NullLoggerFactory.Instance);
return (adapter, new GatewayHistorianDataSource(adapter, NullLogger.Instance));
}
private sealed class ReadService : HistorianRead.HistorianReadBase
{
private readonly List _modes = [];
public Func? Fault { get; init; }
public IReadOnlyList Modes { get { lock (_modes) return _modes.ToList(); } }
public override async Task ReadAggregate(ReadAggregateRequest request, IServerStreamWriter stream,
ServerCallContext context)
{
lock (_modes) _modes.Add(request.Mode);
if (Fault is not null) throw Fault();
var interval = request.Interval.ToTimeSpan();
for (var t = request.StartTime.ToDateTime(); t < request.EndTime.ToDateTime(); t += interval)
await stream.WriteAsync(new HistorianAggregateSample
{
Value = 29.5, OpcQuality = 192, StartTime = Timestamp.FromDateTime(t), EndTime = Timestamp.FromDateTime(t + interval),
});
}
}
/// Every tag exists (GetTagMetadata answers metadata), so the read reaches ReadAggregate.
private sealed class TagsService : HistorianTags.HistorianTagsBase
{
public override Task GetTagMetadata(GetTagMetadataRequest request, ServerCallContext context) =>
Task.FromResult(new GetTagMetadataReply { Metadata = new HistorianTagMetadata { Name = request.Tag } });
}
private sealed class Server(WebApplication app, int port) : IAsyncDisposable
{
public int Port { get; } = port;
public async ValueTask DisposeAsync()
{
await app.StopAsync();
await app.DisposeAsync();
}
}
private static async Task StartServerAsync(ReadService read)
{
var builder = WebApplication.CreateSlimBuilder();
builder.Logging.ClearProviders();
builder.WebHost.ConfigureKestrel(k => k.Listen(IPAddress.Loopback, 0, o => o.Protocols = HttpProtocols.Http2));
builder.Services.AddGrpc();
builder.Services.AddSingleton(read);
builder.Services.AddSingleton();
var app = builder.Build();
app.MapGrpcService();
app.MapGrpcService();
await app.StartAsync();
return new Server(app, new Uri(app.Urls.First()).Port);
}
}