using System.Buffers.Binary; using System.Net; using Google.Protobuf; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; /// /// H2 consumer: as an — header only toward an /// endpoint that advertised history, unsupported answers, per-call deadline = min(remaining, HistoryTimeout), chunk /// assembly within the request budget, a resumed read pinned to its issuing endpoint, release forwarding. /// [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H2")] public sealed class GrpcDataHistoryClientTests { private static readonly DataLimits Limits = new(16, 16, 1 << 20, 16, 4, 1 << 20, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)); private static readonly DataView View = new(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x"); private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(20), 16, 1 << 22); private static readonly DataHistoryCapabilities Caps = new(true, true, true, ["Average"], 1, 100, 4, TimeSpan.FromSeconds(60)); private static DataHistoryReadRequest Request(byte[]? continuation = null) => new(new DataHistoryRawDetails(null, DateTimeOffset.UnixEpoch.AddDays(1), 2, false), [new("a", View, null, continuation)], Budget); [Fact] public async Task An_origin_without_history_answers_unsupported_and_no_HistoryRead_rpc_is_sent() { var a = new Endpoint("a", history: false); await using var connection = Connect([a]); var results = await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken); results.Single().StatusCode.ShouldBe(0x80720000u); a.HistoryCalls.ShouldBe(0); a.Headers.ShouldAllBe(x => x.Path.EndsWith("/GetCapabilities", StringComparison.Ordinal) && x.Features == "history"); } [Fact] public async Task Failed_precondition_from_the_origin_is_unsupported_never_a_transport_fault() { var a = new Endpoint("a") { Fail = Grpc.Core.StatusCode.FailedPrecondition }; await using var connection = Connect([a]); (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x80720000u); var b = new Endpoint("b") { Fail = Grpc.Core.StatusCode.Unimplemented }; await using var v1 = Connect([b]); (await v1.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x80720000u); } [Fact] public async Task The_header_and_the_deadline_follow_the_advertised_endpoint_and_HistoryTimeout() { var a = new Endpoint("a"); await using var connection = Connect([a], historyTimeout: TimeSpan.FromSeconds(2)); var results = await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken); results.Single().StatusCode.ShouldBe(0u); results.Single().Samples.Count.ShouldBe(2); a.Headers.Where(x => x.Path.EndsWith("/HistoryRead", StringComparison.Ordinal)).ShouldAllBe(x => x.Features == "history"); a.LastTimeout.ShouldNotBeNull(); a.LastTimeout!.Value.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(2.5), "min(remaining 20 s, HistoryTimeout 2 s)"); a.LastBudgetTimeout.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(2)); foreach (var r in results) r.Dispose(); } [Fact] public async Task Chunks_are_assembled_and_the_page_continuation_is_wrapped_with_its_endpoint() { var a = new Endpoint("a") { Chunks = 3, PageToken = [9, 9, 9] }; await using var connection = Connect([a]); var result = (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single(); result.ChunkContinues.ShouldBeFalse(); result.Samples.Count.ShouldBe(6, "three chunks of two"); a.HistoryCalls.ShouldBe(3); GrpcDataConnection.TryUnwrap(result.Continuation!, out var endpoint, out var serving, out var token).ShouldBeTrue(); endpoint.ShouldBe(0); serving.ShouldBe("boot-a"); token.ShouldBe(new byte[] { 9, 9, 9 }); result.Dispose(); } [Fact] public async Task Exceeding_the_assembly_budget_is_BadTooManyOperations() { var a = new Endpoint("a") { Chunks = 50 }; await using var connection = Connect([a]); var tight = Request() with { Budget = Budget with { MaxBytes = 2048 } }; (await connection.ReadHistoryAsync(tight, TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x80100000u); } [Fact] public async Task A_fresh_read_may_move_endpoint_but_a_resumed_read_never_does() { var a = new Endpoint("a") { Unavailable = true }; var b = new Endpoint("b") { PageToken = [1, 2, 3] }; await using var connection = Connect([a, b]); var fresh = (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single(); fresh.StatusCode.ShouldBe(0u, "the fresh read moved to b"); var token = fresh.Continuation!; GrpcDataConnection.TryUnwrap(token, out var endpoint, out _, out _).ShouldBeTrue(); endpoint.ShouldBe(1); // b now fails; a resume must not move to a (which would not know the token). b.Unavailable = true; a.Unavailable = false; var resumed = (await connection.ReadHistoryAsync(Request(token), TestContext.Current.CancellationToken)).Single(); resumed.StatusCode.ShouldBe(0x804A0000u); a.HistoryCalls.ShouldBe(0); // b came back under a new incarnation (restart/failover): its old tokens are invalid without asking it. b.Unavailable = false; b.Incarnation = "boot-b2"; var after = (await connection.ReadHistoryAsync(Request(token), TestContext.Current.CancellationToken)).Single(); after.StatusCode.ShouldBe(0x804A0000u); b.LastContinuations.ShouldBeEmpty(); fresh.Dispose(); } [Fact] public async Task A_resumed_read_sends_the_origins_own_token_and_release_forwards_it_to_the_issuing_endpoint() { var a = new Endpoint("a") { PageToken = [4, 5, 6] }; await using var connection = Connect([a]); var first = (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single(); (await connection.ReadHistoryAsync(Request(first.Continuation), TestContext.Current.CancellationToken)).Single().Dispose(); a.LastContinuations.Single().ShouldBe(new byte[] { 4, 5, 6 }, "the envelope is unwrapped before it goes on the wire"); await connection.ReleaseHistoryAsync([first.Continuation!], TestContext.Current.CancellationToken); a.Released.Single().ShouldBe(new byte[] { 4, 5, 6 }); // A malformed token is invalid locally. (await connection.ReadHistoryAsync(Request([1, 2]), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x804A0000u); first.Dispose(); } [Fact] public async Task A_fresh_read_moves_past_a_not_ready_or_ungranted_endpoint() { var a = new Endpoint("a") { Ready = false }; var b = new Endpoint("b") { Granted = false }; var c = new Endpoint("c"); await using var connection = Connect([a, b, c]); var result = (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single(); result.StatusCode.ShouldBe(0u); c.HistoryCalls.ShouldBe(1); (a.HistoryCalls + b.HistoryCalls).ShouldBe(0); result.Dispose(); // Every endpoint without history ⇒ unsupported. c.Granted = false; (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x80720000u); } [Fact] public async Task A_malformed_answer_is_an_endpoint_failure_for_a_fresh_read_and_never_escapes() { var a = new Endpoint("a") { Malformed = true }; var b = new Endpoint("b") { PageToken = [3] }; await using var connection = Connect([a, b]); var fresh = (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single(); fresh.StatusCode.ShouldBe(0u, "moved to b"); // b now answers malformed: the resumed item is ContinuationPointInvalid, a fresh item in the same batch is not. b.Malformed = true; var mixed = new DataHistoryReadRequest(Request().Details, [new("resumed", View, null, fresh.Continuation), new("fresh", View)], Budget); var results = await connection.ReadHistoryAsync(mixed, TestContext.Current.CancellationToken); results[0].StatusCode.ShouldBe(0x804A0000u); results[1].StatusCode.ShouldBe(0x80310000u); fresh.Dispose(); } [Fact] public async Task A_server_cancel_without_a_caller_cancel_is_BadTimeout_and_a_caller_cancel_throws() { var a = new Endpoint("a") { Fail = Grpc.Core.StatusCode.Cancelled }; await using var connection = Connect([a]); (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x800A0000u); (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x800A0000u, "a server-side timeout is not an endpoint failure (no discovery backoff)"); using var cancelled = new CancellationTokenSource(); await cancelled.CancelAsync(); await Should.ThrowAsync(() => connection.ReadHistoryAsync(Request(), cancelled.Token)); } [Fact] public async Task Discovery_backoff_is_honoured_on_the_history_path() { var a = new Endpoint("a") { Unavailable = true }; await using var connection = Connect([a]); (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x80310000u); var probes = a.Headers.Count; (await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x80310000u); a.Headers.Count.ShouldBe(probes, "backing off: no new probe"); } private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? historyTimeout = null) { var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); var router = new Router(endpoints); return new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), endpoints.Select(e => new Uri($"https://{e.Name}.test")), new Security(router), manager.Acquire("link"), 1 << 22, endpoints.Length, eligibleNodeIds: endpoints.Select(e => e.Name).ToHashSet()) { HistoryTimeout = historyTimeout ?? TimeSpan.FromSeconds(30) }; } internal sealed class Endpoint(string name, bool history = true) { public string Name { get; } = name; public string Incarnation { get; set; } = "boot-" + name; public bool Unavailable { get; set; } public Grpc.Core.StatusCode? Fail { get; set; } public bool Ready { get; set; } = true; public bool Granted { get; set; } = true; public bool Malformed { get; set; } public int Chunks { get; init; } = 1; public byte[]? PageToken { get; init; } public int HistoryCalls; public List<(string Path, string? Features)> Headers { get; } = []; public List LastContinuations { get; private set; } = []; public List Released { get; } = []; public TimeSpan? LastTimeout { get; private set; } public TimeSpan LastBudgetTimeout { get; private set; } private readonly Dictionary _chunkLeft = new(); public ServingIdentity Serving => new(Name, Incarnation, "Primary", 1, 1, 1); public async Task HandleAsync(HttpRequestMessage request, CancellationToken token) { var path = request.RequestUri!.AbsolutePath; lock (Headers) Headers.Add((path, request.Headers.TryGetValues("x-otopcua-data-features", out var v) ? string.Join(",", v) : null)); if (Unavailable) return Status(Grpc.Core.StatusCode.Unavailable); IMessage message; if (path.EndsWith("/GetCapabilities", StringComparison.Ordinal)) { var asked = request.Headers.Contains("x-otopcua-data-features"); var caps = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 5, Serving, Ready ? DataReadiness.Ready : DataReadiness.Unavailable, !Ready ? DataOperations.None : DataOperationSets.V1 | (history && asked && Granted ? DataOperations.HistoryRead : DataOperations.None), new HashSet { DataValueKind.Double }, Limits, false, 0, "c", true, true, true, true, true, history && asked ? Caps : null)); message = caps; } else { Interlocked.Increment(ref HistoryCalls); if (Fail is { } fail) return Status(fail); if (request.Headers.TryGetValues("grpc-timeout", out var timeouts)) LastTimeout = ParseTimeout(timeouts.Single()); var bytes = await request.Content!.ReadAsByteArrayAsync(token); var wire = W.HistoryReadRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray()); LastBudgetTimeout = TimeSpan.FromTicks(wire.Budget.TimeoutTicks); var response = new W.HistoryReadResponse { Serving = DataProtoMapper.EncodeServing(Serving) }; if (wire.ReleaseContinuations) { foreach (var item in wire.Items) Released.Add(item.Continuation.ToByteArray()); foreach (var item in wire.Items) response.Items.Add(new W.HistoryReadResult { CorrelationId = item.CorrelationId }); } else { LastContinuations = wire.Items.Where(x => x.HasContinuation).Select(x => x.Continuation.ToByteArray()).ToList(); foreach (var item in wire.Items) { var key = item.CorrelationId; int left; lock (_chunkLeft) left = _chunkLeft[key] = item.HasContinuation && _chunkLeft.TryGetValue(key, out var l) && l > 0 ? l - 1 : Chunks - 1; using var s1 = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 1.0), 0, DateTimeOffset.UnixEpoch, null); using var s2 = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 2.0), 0, null, null); var result = new DataHistoryReadResult(key, 0, [s1, s2], left > 0 ? [7, 7] : PageToken, null, left > 0); response.Items.Add(DataHistoryProtoMapper.EncodeResult(result)); if (Malformed) response.Items[^1].CorrelationId = "not-" + key; } } message = response; } var payload = message.ToByteArray(); var framed = new byte[payload.Length + 5]; BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); payload.CopyTo(framed, 5); var ok = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) }; ok.Content.Headers.ContentType = new("application/grpc"); ok.TrailingHeaders.Add("grpc-status", "0"); return ok; } private static HttpResponseMessage Status(Grpc.Core.StatusCode code) { var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent([]) }; response.Content.Headers.ContentType = new("application/grpc"); response.Headers.Add("grpc-status", ((int)code).ToString(System.Globalization.CultureInfo.InvariantCulture)); response.Headers.Add("grpc-message", code == Grpc.Core.StatusCode.FailedPrecondition ? "feature not negotiated" : "x"); return response; } private static TimeSpan ParseTimeout(string value) { var amount = long.Parse(value[..^1], System.Globalization.CultureInfo.InvariantCulture); return value[^1] switch { 'H' => TimeSpan.FromHours(amount), 'M' => TimeSpan.FromMinutes(amount), 'S' => TimeSpan.FromSeconds(amount), 'm' => TimeSpan.FromMilliseconds(amount), 'u' => TimeSpan.FromTicks(amount * 10), _ => TimeSpan.FromTicks(amount / 100), }; } } private sealed class Router(Endpoint[] endpoints) : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => endpoints.Single(e => request.RequestUri!.Host == e.Name + ".test").HandleAsync(request, cancellationToken); } private sealed class Security(HttpMessageHandler handler) : IDataConnectionSecurityProvider { public event Action? Changed { add { } remove { } } public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => ValueTask.FromResult(new("v1", "ca1", "key", () => new NonDisposing(handler))); } // Each channel disposes its handler; the shared router must survive that. private sealed class NonDisposing(HttpMessageHandler inner) : HttpMessageHandler { private readonly HttpMessageInvoker _invoker = new(inner, disposeHandler: false); protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => _invoker.SendAsync(request, cancellationToken); } }