1237e9e6d1
D1: a caller cancel (the projected deadline) during the connection's capability probe escaped as RpcException(Cancelled) and faulted the whole HistoryRead; it is now OperationCanceledException, the probe is capped by HistoryTimeout, and ProjectedHistoryAccess fails any escaping fault per node (BadTimeout when the deadline fired) and releases every cursor it owns. D4: calls are sub-batched at min(the deployed connection's batch, the origin's advertised MaxBatchItems) and at most one item per 256 B of the remaining assembly budget; a shortfall is BadTooManyOperations per node, never an endpoint failure. D6: the release flush is re-armed from a flag under its gate (no lost wake-up) and the stop source is never disposed under a running flush. D7: calls are runs of consecutive request positions read in request order, then the budget is charged in request order. Float32 node over a Double-returning backend reads Good Singles end to end (no KindMatches defect). Red/green for D1/D4/D7 by mutation; D6's race did not reproduce red.
373 lines
22 KiB
C#
373 lines
22 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]
|
|
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)
|
|
{
|
|
var manager = new DataConnectionManager("consumer", 1);
|
|
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 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;
|
|
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 }, 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);
|
|
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)
|
|
{
|
|
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<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);
|
|
}
|
|
}
|