Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs
T
Joseph Doherty 30d66fdc7c fix(grpc-data): H3 review round 3 S5 — a cancel by redeploy/shutdown is not a timeout
GrpcDataConnection.ServeAsync mapped RpcException(Cancelled) without a caller
cancel to BadTimeout even when the linked channel-retired / scope / shutdown
token fired. That case is now BadNoCommunication (resumed:
BadContinuationPointInvalid), releases held chunk tokens and stops a split
request sending further sub-batches. ProjectedHistoryAccess's outer catch no
longer reads any escaped OperationCanceledException as a timeout: only the
caller's cancel or the deadline is BadTimeout, otherwise classified as
FailCancelled does. Red on revert (client test: scope moved mid-call); the
outer-catch change has no dedicated test (nothing reachable throws past
ReadGroupAsync's own catch).
2026-11-24 07:11:06 -05:00

545 lines
32 KiB
C#

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;
/// <summary>
/// H2 consumer: <see cref="GrpcDataConnection"/> as an <see cref="IDataHistoryService"/> — 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.
/// </summary>
[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<OperationCanceledException>(() => 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");
}
[Fact]
public async Task A_caller_cancel_during_the_call_surfaces_as_OperationCanceledException()
{
var a = new Endpoint("a") { Delay = TimeSpan.FromSeconds(30) };
await using var connection = Connect([a]);
using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
await Should.ThrowAsync<OperationCanceledException>(() => connection.ReadHistoryAsync(Request(), cancel.Token));
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_caller_cancel_during_the_capability_probe_is_an_OperationCanceledException_never_an_RpcException()
{
// H3 review D1: the probe that never answers used to surface RpcException(Cancelled) and fault the consumer's HistoryRead.
var a = new Endpoint("a") { ProbeDelay = TimeSpan.FromSeconds(30) };
await using var connection = Connect([a]);
using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
var error = await Should.ThrowAsync<OperationCanceledException>(() => connection.ReadHistoryAsync(Request(), cancel.Token));
error.ShouldNotBeAssignableTo<Grpc.Core.RpcException>();
a.HistoryCalls.ShouldBe(0);
}
[Fact]
[Trait("Phase", "H3")]
public async Task The_capability_probe_is_capped_by_HistoryTimeout_too()
{
var a = new Endpoint("a");
await using var connection = Connect([a], historyTimeout: TimeSpan.FromSeconds(2));
var request = Request() with { Budget = Request().Budget with { Timeout = TimeSpan.FromMinutes(10) } };
(await connection.ReadHistoryAsync(request, TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0u);
a.LastProbeTimeout.ShouldNotBeNull();
a.LastProbeTimeout!.Value.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(2));
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_request_larger_than_the_endpoints_advertised_batch_is_split_from_the_negotiated_capabilities()
{
// H3 review round 2: the split uses the capabilities the history call itself negotiated — no extra probe.
var a = new Endpoint("a") { BatchItems = 2 };
await using var connection = Connect([a]);
var request = new DataHistoryReadRequest(Request().Details,
Enumerable.Range(0, 5).Select(i => new DataHistoryReadItem("n" + i, View)).ToArray(), Budget);
var results = await connection.ReadHistoryAsync(request, TestContext.Current.CancellationToken);
results.Select(r => r.CorrelationId).ShouldBe(["n0", "n1", "n2", "n3", "n4"]);
results.ShouldAllBe(r => r.StatusCode == 0u && r.Samples.Count == 2);
a.CallSizes.ShouldBe([2, 2, 1]);
a.Headers.Count(h => h.Path.EndsWith("/GetCapabilities", StringComparison.Ordinal)).ShouldBe(1, "one negotiation for the whole request");
foreach (var r in results) r.Dispose();
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_cancel_during_a_multi_node_read_leaves_the_connection_usable_without_backoff()
{
var a = new Endpoint("a") { ProbeDelay = TimeSpan.FromSeconds(30) };
await using var connection = Connect([a]);
var request = new DataHistoryReadRequest(Request().Details,
Enumerable.Range(0, 3).Select(i => new DataHistoryReadItem("n" + i, View)).ToArray(), Budget);
using (var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(200)))
await Should.ThrowAsync<OperationCanceledException>(() => connection.ReadHistoryAsync(request, cancel.Token));
a.ProbeDelay = null;
var again = await connection.ReadHistoryAsync(request, TestContext.Current.CancellationToken);
again.ShouldAllBe(r => r.StatusCode == 0u, "a cancel is not an endpoint failure: no discovery backoff");
foreach (var r in again) r.Dispose();
}
// ---- H3 review round 3 -------------------------------------------------------------------------------------------
private static readonly long SampleBytes = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 1.0), 0, null, null)
.Value.EstimatedRetainedBytes; // the fake answers two Double samples per item per chunk
private static DataHistoryReadRequest Many(int count, long? maxBytes = null) => new(Request().Details,
Enumerable.Range(0, count).Select(i => new DataHistoryReadItem("n" + i, View)).ToArray(), maxBytes is { } b ? Budget with { MaxBytes = b } : Budget);
private static async Task AwaitReleased(Endpoint a, Func<byte[][], bool> done)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
while (DateTime.UtcNow < deadline)
{
byte[][] released;
lock (a.Released) released = a.Released.ToArray();
if (done(released)) return;
await Task.Delay(20, TestContext.Current.CancellationToken);
}
}
private static int ReleasedCount(Endpoint a, byte[] token) { lock (a.Released) return a.Released.Count(t => t.SequenceEqual(token)); }
[Fact]
[Trait("Phase", "H3")]
public async Task A_cancel_in_a_later_sub_batch_releases_the_earlier_sub_batches_new_continuations()
{
// S1: sub-batch 1 answered (two new page continuations); the caller cancels during sub-batch 2 — nothing is stranded.
var a = new Endpoint("a") { BatchItems = 2, PageToken = [9, 9, 9], HangOnDataCall = 2 };
await using var connection = Connect([a]);
using var cancel = new CancellationTokenSource();
var read = connection.ReadHistoryAsync(Many(4), cancel.Token);
var deadline = DateTime.UtcNow.AddSeconds(10);
while (Volatile.Read(ref a.DataCalls) < 2 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken);
await cancel.CancelAsync();
await Should.ThrowAsync<OperationCanceledException>(() => read);
await AwaitReleased(a, r => r.Count(t => t.SequenceEqual(new byte[] { 9, 9, 9 })) >= 2);
ReleasedCount(a, [9, 9, 9]).ShouldBe(2, "both continuations sub-batch 1 opened are released");
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_later_sub_batch_is_trimmed_to_the_origins_byte_admission_and_the_rest_is_a_consumer_budget_refusal()
{
// S2: after sub-batch 1 only room for ONE item is left (256 B); sending two would break the origin's count <= MaxBytes/256
// rule (an RpcException ⇒ a recorded endpoint failure). Trimmed: [2, 1], the rest refused unsent, no endpoint failure.
var a = new Endpoint("a") { BatchItems = 2, EnforceAdmission = true };
await using var connection = Connect([a]);
var results = await connection.ReadHistoryAsync(Many(4, 4 * SampleBytes + 256), TestContext.Current.CancellationToken);
results.Take(2).ShouldAllBe(r => r.StatusCode == 0u && r.Samples.Count == 2);
results.Skip(2).ShouldAllBe(r => r.StatusCode == 0x80100000u && r.ConsumerBudgetRefused);
a.CallSizes.ShouldBe([2, 1]);
foreach (var r in results) r.Dispose();
var again = await connection.ReadHistoryAsync(Many(1), TestContext.Current.CancellationToken);
again.Single().StatusCode.ShouldBe(0u, "a budget refusal is not an endpoint failure");
foreach (var r in again) r.Dispose();
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_sub_batch_whose_assembly_overflows_spends_the_budget_and_nothing_more_is_sent()
{
// S3: sub-batch 2 refuses n3 inside its own assembly while what was KEPT is still below the budget — n4, n5 unsent.
var a = new Endpoint("a") { BatchItems = 2 };
await using var connection = Connect([a]);
var results = await connection.ReadHistoryAsync(Many(6, 7 * SampleBytes), TestContext.Current.CancellationToken);
results.Take(3).ShouldAllBe(r => r.StatusCode == 0u);
results.Skip(3).ShouldAllBe(r => r.StatusCode == 0x80100000u && r.ConsumerBudgetRefused);
a.CallSizes.ShouldBe([2, 2]);
foreach (var r in results) r.Dispose();
}
[Fact]
[Trait("Phase", "H3")]
public async Task After_a_sub_batch_endpoint_failure_nothing_more_is_sent_to_that_endpoint()
{
// Nit (a): sub-batch 2 fails (recorded); sub-batch 3 is answered unsent.
var a = new Endpoint("a") { BatchItems = 2, FailAfterFirst = Grpc.Core.StatusCode.Internal };
await using var connection = Connect([a]);
var results = await connection.ReadHistoryAsync(Many(5), TestContext.Current.CancellationToken);
results.Take(2).ShouldAllBe(r => r.StatusCode == 0u);
results.Skip(2).ShouldAllBe(r => r.StatusCode == 0x80310000u);
a.CallSizes.ShouldBe([2, 2]);
foreach (var r in results) r.Dispose();
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_rejected_follow_up_chunk_releases_every_token_the_assembly_holds()
{
// S6: n0 completes on call 1 (a new page continuation in final[]); n1 continues; call 2's answer is malformed.
var a = new Endpoint("a") { PageToken = [9, 9, 9], Chunks = 3, MalformedFromDataCall = 2 };
a.ChunksByItem["n0"] = 1;
await using var connection = Connect([a]);
var results = await connection.ReadHistoryAsync(Many(2), TestContext.Current.CancellationToken);
results.ShouldAllBe(r => r.StatusCode == 0x80310000u);
await AwaitReleased(a, r => r.Any(t => t.SequenceEqual(new byte[] { 9, 9, 9 })) && r.Any(t => t.SequenceEqual(new byte[] { 7, 7 })));
ReleasedCount(a, [9, 9, 9]).ShouldBe(1, "n0's finished continuation is released");
ReleasedCount(a, [7, 7]).ShouldBeGreaterThan(0, "n1's chunk tokens are released");
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_call_cancelled_by_a_scope_move_is_not_a_timeout()
{
// S5: neither the caller nor the deadline cancelled the call — the connection's scope moved (a redeploy).
DataConnectionManager? manager = null;
var a = new Endpoint("a") { HangOnDataCall = 1 };
await using var connection = Connect([a], onManager: m => manager = m);
var request = new DataHistoryReadRequest(Request().Details,
[new("fresh", View), new("resumed", View, null, GrpcDataConnection.Wrap(0, "boot-a", [1, 2]))], Budget);
var read = connection.ReadHistoryAsync(request, TestContext.Current.CancellationToken);
var deadline = DateTime.UtcNow.AddSeconds(10);
while (Volatile.Read(ref a.DataCalls) < 1 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken);
manager!.ApplyScope(new Dictionary<string, IReadOnlySet<string>>());
var results = await read;
results[0].StatusCode.ShouldBe(0x80310000u, "fresh: BadNoCommunication, not BadTimeout");
results[1].StatusCode.ShouldBe(0x804A0000u, "resumed: BadContinuationPointInvalid");
}
[Fact]
public async Task A_failure_mid_assembly_releases_the_origin_chunk_tokens_it_holds()
{
var a = new Endpoint("a") { Chunks = 3, FailAfterFirst = Grpc.Core.StatusCode.Internal };
await using var connection = Connect([a]);
(await connection.ReadHistoryAsync(Request(), TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0x80310000u);
var deadline = DateTime.UtcNow.AddSeconds(10);
while (a.Released.Count == 0 && DateTime.UtcNow < deadline) await Task.Delay(20, TestContext.Current.CancellationToken);
a.Released.ShouldContain(t => t.SequenceEqual(new byte[] { 7, 7 }), "the chunk token the failed follow-up carried is released");
}
private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? historyTimeout = null, Action<DataConnectionManager>? onManager = null)
{
var manager = new DataConnectionManager("consumer", 1);
onManager?.Invoke(manager);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "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; }
/// <summary>Delay before answering a HistoryRead (honours the request's token).</summary>
public TimeSpan? Delay { get; set; }
/// <summary>Delay before answering the capability probe (honours the request's token).</summary>
public TimeSpan? ProbeDelay { get; set; }
/// <summary>The advertised MaxBatchItems (default: the shared limits').</summary>
public int? BatchItems { get; set; }
/// <summary>The item count of every HistoryRead call.</summary>
public List<int> CallSizes { get; } = [];
/// <summary>The grpc-timeout of the last capability probe.</summary>
public TimeSpan? LastProbeTimeout { get; private set; }
/// <summary>Fail every HistoryRead after the first with this status.</summary>
public Grpc.Core.StatusCode? FailAfterFirst { get; set; }
public int Chunks { get; init; } = 1;
/// <summary>Per correlation id chunk counts (overrides <see cref="Chunks"/>).</summary>
public Dictionary<string, int> ChunksByItem { get; } = new();
/// <summary>Refuse a call carrying more than one item per 256 B of its byte budget (the origin's admission rule).</summary>
public bool EnforceAdmission { get; set; }
/// <summary>The data (non-release) HistoryRead call that never answers (honours the request's token).</summary>
public int? HangOnDataCall { get; set; }
/// <summary>From this data call on, answers carry unexpected correlation ids.</summary>
public int? MalformedFromDataCall { get; set; }
public int DataCalls;
public byte[]? PageToken { get; init; }
public int HistoryCalls;
public List<(string Path, string? Features)> Headers { get; } = [];
public List<byte[]> LastContinuations { get; private set; } = [];
public List<byte[]> Released { get; } = [];
public TimeSpan? LastTimeout { get; private set; }
public TimeSpan LastBudgetTimeout { get; private set; }
private readonly Dictionary<string, int> _chunkLeft = new();
public ServingIdentity Serving => new(Name, Incarnation, "Primary", 1, 1, 1);
public async Task<HttpResponseMessage> 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))
{
if (request.Headers.TryGetValues("grpc-timeout", out var probeTimeouts)) LastProbeTimeout = ParseTimeout(probeTimeouts.Single());
if (ProbeDelay is { } probeDelay) await Task.Delay(probeDelay, token);
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> { DataValueKind.Double }, BatchItems is { } b ? Limits with { MaxBatchItems = b } : Limits, false, 0, "c", true, true, true, true, true,
history && asked ? Caps : null));
message = caps;
}
else
{
var call = Interlocked.Increment(ref HistoryCalls);
if (Fail is { } fail) return Status(fail);
if (Delay is { } delay) await Task.Delay(delay, token);
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);
if (!wire.ReleaseContinuations) lock (CallSizes) CallSizes.Add(wire.Items.Count);
var dataCall = wire.ReleaseContinuations ? 0 : Interlocked.Increment(ref DataCalls);
if (EnforceAdmission && !wire.ReleaseContinuations && wire.Items.Count > wire.Budget.MaxBytes / 256)
return Status(Grpc.Core.StatusCode.InvalidArgument);
if (dataCall != 0 && dataCall == HangOnDataCall) await Task.Delay(Timeout.Infinite, token);
var response = new W.HistoryReadResponse { Serving = DataProtoMapper.EncodeServing(Serving) };
if (!wire.ReleaseContinuations && call > 1 && FailAfterFirst is { } later)
{
LastContinuations = wire.Items.Where(x => x.HasContinuation).Select(x => x.Continuation.ToByteArray()).ToList();
return Status(later);
}
if (wire.ReleaseContinuations)
{
lock (Released) 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
: (ChunksByItem.TryGetValue(key, out var c) ? c : 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 || dataCall >= MalformedFromDataCall) 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<HttpResponseMessage> 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<string>? Changed { add { } remove { } }
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
ValueTask.FromResult<DataConnectionSecurity?>(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<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
_invoker.SendAsync(request, cancellationToken);
}
}