perf: measure grpc fanout and recovery bounds
This commit is contained in:
+194
@@ -0,0 +1,194 @@
|
||||
using Grpc.Core;
|
||||
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests.DataConnections;
|
||||
|
||||
[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P11")]
|
||||
public sealed class GrpcDataReconnectStormWireTests
|
||||
{
|
||||
[Fact(Timeout = 60000)]
|
||||
public async Task Concurrent_reconnects_after_active_loss_get_new_snapshots_and_drain_old_streams()
|
||||
{
|
||||
const int clients = 4;
|
||||
using var active = new ControlledOrigin(new("node-a", "old-boot", "Primary", 1, 1, 1), 42, true);
|
||||
using var standby = new ControlledOrigin(new("node-b", "new-boot", "Primary", 1, 1, 2), 43, false);
|
||||
await using var first = await GrpcDataWireFixture.StartAsync(HttpProtocols.Http2, new(active.Create));
|
||||
await using var second = await GrpcDataWireFixture.StartAsync(HttpProtocols.Http2, new(standby.Create));
|
||||
var trust = new DataConnectionTrustPolicy(1, [first.Ca, second.Ca]);
|
||||
var security = new EndpointSecurity(first, second, trust);
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
var endpointA = new UriBuilder("https", "localhost", first.TlsAddress.Port).Uri;
|
||||
var endpointB = new UriBuilder("https", "localhost", second.TlsAddress.Port).Uri;
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "cluster", null),
|
||||
[endpointA, endpointB], security, manager.Acquire("link"), 65536, 2,
|
||||
eligibleNodeIds: new HashSet<string> { "node-a", "node-b" }, maxStreams: clients, maxMonitoredItems: 8);
|
||||
var token = TestContext.Current.CancellationToken;
|
||||
var old = await Task.WhenAll(Enumerable.Range(0, clients).Select(i => OpenAsync(connection, i, 1, token)));
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(old.Select(x => ReadSnapshotAsync(x.Reader, active.Serving, 42, token)));
|
||||
active.ActiveStreams.ShouldBe(clients);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => connection.SubscribeAsync(token));
|
||||
active.ActiveStreams.ShouldBe(clients, "the stream limit must reject before another physical subscription");
|
||||
|
||||
using var value = DataValue.FromScalar(DataValueKind.Int32, 8);
|
||||
var request = new WriteBatch([new("write", "operation-1", View, value, 1, "old-boot", TimeSpan.FromSeconds(5), 1)], Budget);
|
||||
var outcome = await connection.WriteAsync(request, token);
|
||||
outcome.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
active.WriteCalls.ShouldBe(1); standby.WriteCalls.ShouldBe(0);
|
||||
|
||||
active.Lose(); standby.Promote();
|
||||
await Task.WhenAll(old.Select(async x =>
|
||||
{
|
||||
try
|
||||
{
|
||||
while (await x.Reader.MoveNextAsync())
|
||||
{
|
||||
var frame = x.Reader.Current;
|
||||
if (frame is DataSubscriptionValues values)
|
||||
{ values.Dispose(); throw new InvalidOperationException("An old stream delivered values after its origin was lost."); }
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is RpcException or OperationCanceledException or System.IO.IOException) { }
|
||||
finally { await x.Reader.DisposeAsync(); await x.Stream.DisposeAsync(); }
|
||||
}));
|
||||
await active.Drained.Task.WaitAsync(TimeSpan.FromSeconds(10), token);
|
||||
active.ActiveStreams.ShouldBe(0);
|
||||
await first.StopAsync();
|
||||
standby.WriteCalls.ShouldBe(0, "an ambiguous write is never replayed after failover");
|
||||
|
||||
var renewed = await Task.WhenAll(Enumerable.Range(0, clients).Select(i => OpenAsync(connection, i, 2, token)));
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(renewed.Select(x => ReadSnapshotAsync(x.Reader, standby.Serving, 43, token)));
|
||||
standby.ActiveStreams.ShouldBe(clients);
|
||||
standby.WriteCalls.ShouldBe(0);
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var item in renewed) { await item.Reader.DisposeAsync(); await item.Stream.DisposeAsync(); }
|
||||
}
|
||||
await standby.Drained.Task.WaitAsync(TimeSpan.FromSeconds(10), token);
|
||||
standby.ActiveStreams.ShouldBe(0);
|
||||
}
|
||||
finally
|
||||
{
|
||||
active.Lose(); standby.Lose();
|
||||
foreach (var item in old) { await item.Reader.DisposeAsync(); await item.Stream.DisposeAsync(); }
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 8, 65536);
|
||||
private static readonly DataView View = new(new("cluster", "urn:test", "string", "source"), DataRealm.Raw, null, 0, "source");
|
||||
private static readonly DataSubscriptionSettings Settings = new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
|
||||
private static async Task<(IDataSubscription Stream, IAsyncEnumerator<DataSubscriptionFrame> Reader)> OpenAsync(GrpcDataConnection connection, int index, long epoch, CancellationToken token)
|
||||
{
|
||||
var stream = await connection.SubscribeAsync(token);
|
||||
try
|
||||
{
|
||||
await stream.SendAsync(new OpenSubscription("storm-" + index, epoch, "open", TimeSpan.FromSeconds(5),
|
||||
[new("item", View, Settings)], false, TimeSpan.FromSeconds(30), Budget), token);
|
||||
return (stream, stream.ReadAllAsync(token).GetAsyncEnumerator(token));
|
||||
}
|
||||
catch { await stream.DisposeAsync(); throw; }
|
||||
}
|
||||
private static async Task ReadSnapshotAsync(IAsyncEnumerator<DataSubscriptionFrame> reader, ServingIdentity serving, int expected, CancellationToken token)
|
||||
{
|
||||
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(10), token)).ShouldBeTrue();
|
||||
reader.Current.ShouldBeOfType<DataSubscriptionAck>().Items.ShouldHaveSingleItem().Status.ShouldBe(DataItemStatus.Good);
|
||||
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(10), token)).ShouldBeTrue();
|
||||
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
|
||||
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(10), token)).ShouldBeTrue();
|
||||
using (var values = reader.Current.ShouldBeOfType<DataSubscriptionValues>())
|
||||
{
|
||||
values.IsSnapshot.ShouldBeTrue();
|
||||
var sample = values.Items.ShouldHaveSingleItem().Sample; sample.Serving.ShouldBe(serving); sample.Value.GetScalar().ShouldBe(expected);
|
||||
}
|
||||
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(10), token)).ShouldBeTrue();
|
||||
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd);
|
||||
}
|
||||
|
||||
private sealed class EndpointSecurity(GrpcDataWireFixture first, GrpcDataWireFixture second, DataConnectionTrustPolicy trust) : IDataConnectionSecurityProvider
|
||||
{
|
||||
public event Action<string>? Changed { add { } remove { } }
|
||||
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken token) =>
|
||||
ValueTask.FromResult<DataConnectionSecurity?>(new("credential", trust.Fingerprint,
|
||||
endpoint.Port == first.TlsAddress.Port ? first.Bearer : second.Bearer, trust.CreateHandler));
|
||||
}
|
||||
private sealed class ControlledOrigin(ServingIdentity serving, int value, bool ready) : IDisposable
|
||||
{
|
||||
private int _ready = ready ? 1 : 0, _active, _writeCalls;
|
||||
private readonly CancellationTokenSource _lost = new();
|
||||
internal readonly TaskCompletionSource Drained = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
internal ServingIdentity Serving => serving;
|
||||
internal int InitialValue => value;
|
||||
internal int ActiveStreams => Volatile.Read(ref _active);
|
||||
internal int WriteCalls => Volatile.Read(ref _writeCalls);
|
||||
internal void Promote() => Volatile.Write(ref _ready, 1);
|
||||
internal void Lose() { Volatile.Write(ref _ready, 0); _lost.Cancel(); if (ActiveStreams == 0) Drained.TrySetResult(); }
|
||||
public void Dispose() => _lost.Dispose();
|
||||
internal IDataConnection Create(DataTarget target) => new Connection(this, target);
|
||||
private sealed class Connection(ControlledOrigin owner, DataTarget target) : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate
|
||||
{
|
||||
public DataTarget Target => target;
|
||||
public TimeProvider Clock => TimeProvider.System;
|
||||
public bool CanPublish(ServingIdentity expected) => Volatile.Read(ref owner._ready) != 0 && expected == owner.Serving;
|
||||
public bool CanPublishCapabilities(DataCapabilities expected) => expected.Serving == owner.Serving && expected.Readiness == (Volatile.Read(ref owner._ready) != 0 ? DataReadiness.Ready : DataReadiness.Unavailable);
|
||||
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken token) => Task.FromResult(new DataCapabilities(1, 3,
|
||||
owner.Serving, Volatile.Read(ref owner._ready) != 0 ? DataReadiness.Ready : DataReadiness.Unavailable,
|
||||
DataOperations.Subscribe | DataOperations.Write, new HashSet<DataValueKind> { DataValueKind.Int32 },
|
||||
new(16, 16, 65536, 8, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)),
|
||||
true, 1, "cluster", true, true, true));
|
||||
public Task<IDataSubscription> SubscribeAsync(CancellationToken token)
|
||||
{ Interlocked.Increment(ref owner._active); return Task.FromResult<IDataSubscription>(new Stream(owner)); }
|
||||
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken token)
|
||||
{ Interlocked.Increment(ref owner._writeCalls); throw new RpcException(new Status(StatusCode.Unavailable, "Simulated lost write reply after dispatch.")); }
|
||||
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken token) => throw new NotSupportedException();
|
||||
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken token) => throw new NotSupportedException();
|
||||
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken token) => throw new NotSupportedException();
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
private sealed class Stream(ControlledOrigin owner) : IDataSubscriptionTransport
|
||||
{
|
||||
private readonly TaskCompletionSource<OpenSubscription> _open = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private int _disposed;
|
||||
public Task SendAsync(DataSubscriptionCommand command, CancellationToken token)
|
||||
{ _open.TrySetResult((OpenSubscription)command); return Task.CompletedTask; }
|
||||
public IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken token) => throw new NotSupportedException();
|
||||
public async Task RunDeliveryAsync(IDataSubscriptionDeliverySink sink, CancellationToken token)
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, owner._lost.Token);
|
||||
var open = await _open.Task.WaitAsync(linked.Token);
|
||||
var handle = new DataItemHandle(open.SubscriptionId, open.StreamEpoch, 1, 1);
|
||||
async Task Send(DataSubscriptionFrame frame)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var prepared = await sink.PrepareAsync(frame, 16384, linked.Token);
|
||||
((IDataPreparedSubscriptionPublication)prepared).SetPublicationGuard(() => Volatile.Read(ref owner._ready) != 0 && !owner._lost.IsCancellationRequested);
|
||||
await sink.WriteAsync(prepared, linked.Token);
|
||||
}
|
||||
finally { (frame as IDisposable)?.Dispose(); }
|
||||
}
|
||||
await Send(new DataSubscriptionAck(open.SubscriptionId, open.StreamEpoch, 1, open.CommandId,
|
||||
[new(open.Items[0].ClientItemId, DataItemStatus.Good, handle, open.Items[0].Settings, null)]));
|
||||
await Send(new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 2, DataStreamControlKind.SnapshotBegin, [], 1, 1, null));
|
||||
await Send(new DataSubscriptionValues(open.SubscriptionId, open.StreamEpoch, 3, true,
|
||||
[new(handle, new(DataValue.FromScalar(DataValueKind.Int32, owner.InitialValue), 0, null, null, owner.Serving, 1), new(TimeSpan.Zero, TimeSpan.Zero), DataReadiness.Ready)]));
|
||||
await Send(new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 4, DataStreamControlKind.SnapshotEnd, [], 1, 1, null));
|
||||
try { await Task.Delay(Timeout.Infinite, linked.Token); } catch (OperationCanceledException) when (linked.IsCancellationRequested) { }
|
||||
}
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 0 && Interlocked.Decrement(ref owner._active) == 0) owner.Drained.TrySetResult();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
using Grpc.Core;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Grpc;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.OpcUa;
|
||||
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P11")]
|
||||
public sealed class GrpcDataCompactNegotiationTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(false, false)]
|
||||
[InlineData(true, true)]
|
||||
public async Task Stream_uses_compact_only_after_explicit_supported_opt_in(bool optIn, bool compact)
|
||||
{
|
||||
var headers = new Metadata(); if (optIn) headers.Add("x-data-compact-codec", "1");
|
||||
var fixture = Create(headers, peerSupportsCompact: true);
|
||||
var writer = new Writer();
|
||||
await fixture.Service.Subscribe(new Reader(), writer, fixture.Context);
|
||||
var frame = writer.Frames.ShouldHaveSingleItem();
|
||||
(frame.CompactValues is not null).ShouldBe(compact);
|
||||
(frame.Values is not null).ShouldBe(!compact);
|
||||
frame.Serving.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Opt_in_does_not_override_a_server_without_the_codec()
|
||||
{
|
||||
var fixture = Create(new Metadata { { "x-data-compact-codec", "1" } }, peerSupportsCompact: false);
|
||||
var writer = new Writer(); await fixture.Service.Subscribe(new Reader(), writer, fixture.Context);
|
||||
writer.Frames.ShouldHaveSingleItem().Values.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("2", false)]
|
||||
[InlineData("1", true)]
|
||||
public async Task Invalid_or_duplicate_codec_header_is_rejected(string value, bool duplicate)
|
||||
{
|
||||
var headers = new Metadata { { "x-data-compact-codec", value } };
|
||||
if (duplicate) headers.Add("x-data-compact-codec", "1");
|
||||
var fixture = Create(headers, peerSupportsCompact: true);
|
||||
var failure = await Should.ThrowAsync<RpcException>(() => fixture.Service.Subscribe(new Reader(), new Writer(), fixture.Context));
|
||||
failure.StatusCode.ShouldBe(StatusCode.InvalidArgument);
|
||||
}
|
||||
|
||||
private static (DataConnectionGrpcService Service, CallContext Context) Create(Metadata headers, bool peerSupportsCompact)
|
||||
{
|
||||
var (bearer, id, hash) = ApiKeySecret.Generate("pepper");
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
authority.Apply("cluster", "v1", [new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash, Enabled = true }],
|
||||
[], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
||||
var authenticator = new DataConnectionAuthenticator(authority, Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System);
|
||||
var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, AllowedHosts = ["source.local"], CertificatePath = "server.pem" };
|
||||
var context = new CallContext(headers); var http = new DefaultHttpContext();
|
||||
http.Connection.LocalPort = 9443; http.Request.Protocol = "HTTP/2"; http.Request.Scheme = "https"; http.Request.Method = "POST";
|
||||
http.Request.Host = new HostString("source.local", 9443); http.Request.Path = context.Method;
|
||||
http.Items[typeof(DataAuthenticatedContext)] = authenticator.Authenticate(bearer);
|
||||
http.Items[typeof(DataTarget)] = new DataTarget(DataTargetMode.Node, "cluster", "node");
|
||||
context.UserState["__HttpContext"] = http;
|
||||
return (new DataConnectionGrpcService(new Factory(peerSupportsCompact), Options.Create(options), authenticator), context);
|
||||
}
|
||||
|
||||
private sealed class Factory(bool compact) : IDataConnectionFactory
|
||||
{ public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) => new Connection(target, compact); }
|
||||
private sealed class Connection(DataTarget target, bool compact) : IDataConnection, IDataConnectionPublicationGate
|
||||
{
|
||||
internal static readonly ServingIdentity Serving = new("node", "boot", "Primary", 1, 1, 1);
|
||||
public DataTarget Target => target;
|
||||
public TimeProvider Clock => TimeProvider.System;
|
||||
public bool CanPublish(ServingIdentity expectedServing) => expectedServing == Serving;
|
||||
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken token) => Task.FromResult(new DataCapabilities(1, 3, Serving, DataReadiness.Ready,
|
||||
DataOperations.Subscribe, new HashSet<DataValueKind> { DataValueKind.Int32 },
|
||||
new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)), compact, compact ? 1 : 0, "cluster", true, true));
|
||||
public Task<IDataSubscription> SubscribeAsync(CancellationToken token) => Task.FromResult<IDataSubscription>(new Subscription());
|
||||
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken token) => throw new NotSupportedException();
|
||||
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken token) => throw new NotSupportedException();
|
||||
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken token) => throw new NotSupportedException();
|
||||
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken token) => throw new NotSupportedException();
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
private sealed class Subscription : IDataSubscriptionTransport
|
||||
{
|
||||
private readonly TaskCompletionSource _opened = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public Task SendAsync(DataSubscriptionCommand command, CancellationToken token) { _opened.TrySetResult(); return Task.CompletedTask; }
|
||||
public IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken token) => throw new NotSupportedException();
|
||||
public async Task RunDeliveryAsync(IDataSubscriptionDeliverySink sink, CancellationToken token)
|
||||
{
|
||||
await _opened.Task.WaitAsync(token);
|
||||
using var frame = new DataSubscriptionValues("s", 1, 1, true,
|
||||
[new(new("s", 1, 1, 1), new(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Connection.Serving, 1), new(TimeSpan.Zero, TimeSpan.Zero), DataReadiness.Ready)]);
|
||||
using var prepared = await sink.PrepareAsync(frame, 16384, token);
|
||||
((IDataPreparedSubscriptionPublication)prepared).SetPublicationGuard(() => true);
|
||||
await sink.WriteAsync(prepared, token);
|
||||
}
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
private sealed class Reader : IAsyncStreamReader<W.SubscriptionCommand>
|
||||
{
|
||||
private int _read;
|
||||
public W.SubscriptionCommand Current { get; private set; } = null!;
|
||||
public async Task<bool> MoveNext(CancellationToken token)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _read, 1) == 0)
|
||||
{
|
||||
Current = DataProtoMapper.EncodeCommand(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [], false,
|
||||
TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, 4096)));
|
||||
return true;
|
||||
}
|
||||
await Task.Delay(Timeout.Infinite, token); return false;
|
||||
}
|
||||
}
|
||||
private sealed class Writer : IServerStreamWriter<W.SubscriptionFrame>
|
||||
{
|
||||
public List<W.SubscriptionFrame> Frames { get; } = [];
|
||||
public WriteOptions? WriteOptions { get; set; }
|
||||
public Task WriteAsync(W.SubscriptionFrame frame) { Frames.Add(frame); return Task.CompletedTask; }
|
||||
public Task WriteAsync(W.SubscriptionFrame frame, CancellationToken cancellationToken) => WriteAsync(frame);
|
||||
}
|
||||
private sealed class CallContext(Metadata headers) : ServerCallContext
|
||||
{
|
||||
protected override string MethodCore => DataConnectionEndpoints.ServicePrefix + "Subscribe";
|
||||
protected override string HostCore => "source.local";
|
||||
protected override string PeerCore => "ipv4:127.0.0.1:0";
|
||||
protected override DateTime DeadlineCore => DateTime.MaxValue;
|
||||
protected override Metadata RequestHeadersCore => headers;
|
||||
protected override CancellationToken CancellationTokenCore => TestContext.Current.CancellationToken;
|
||||
protected override Metadata ResponseTrailersCore { get; } = [];
|
||||
protected override Status StatusCore { get; set; }
|
||||
protected override WriteOptions? WriteOptionsCore { get; set; }
|
||||
protected override AuthContext AuthContextCore => new(null, new Dictionary<string, List<AuthProperty>>());
|
||||
protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) => throw new NotSupportedException();
|
||||
protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) => Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P11")]
|
||||
public sealed class GrpcDataSdkSampleEvidenceTests
|
||||
{
|
||||
[Fact]
|
||||
public void Status_match_only_normalizes_an_empty_datavalue_info_type()
|
||||
{
|
||||
ProjectedMonitoredItem.SameObservedStatus(0x00000400u, 0u).ShouldBeTrue();
|
||||
ProjectedMonitoredItem.SameObservedStatus(0x80000400u, 0x80000000u).ShouldBeTrue();
|
||||
ProjectedMonitoredItem.SameObservedStatus(0x00000480u, 0u).ShouldBeFalse();
|
||||
ProjectedMonitoredItem.SameObservedStatus(0x00001400u, 0u).ShouldBeFalse();
|
||||
ProjectedMonitoredItem.SameObservedStatus(0x40000400u, 0u).ShouldBeFalse();
|
||||
ProjectedMonitoredItem.SameObservedStatus(0x00000800u, 0u).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Repeat_observation_matches_the_same_source_acquisition_without_replacing_queued_evidence()
|
||||
{
|
||||
var identity = new object();
|
||||
var timestamp = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
var sample = new ProjectedValueWrite(DataRealm.Raw, "projected", 1,
|
||||
new ServingIdentity("node", "incarnation", "Primary", 1, 1, 1),
|
||||
new DataValueSnapshot(new[] { 1, 2 }, 0, timestamp, timestamp),
|
||||
new DataAgeBounds(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)), 123,
|
||||
new Proof(identity), SourceVersion: 7);
|
||||
var replay = sample with
|
||||
{
|
||||
Snapshot = sample.Snapshot with { Value = new[] { 1, 2 } },
|
||||
Proof = new Proof(identity), IsCompleteSnapshot = true
|
||||
};
|
||||
ProjectedMonitoredItem.SameAcquisition(sample, replay).ShouldBeTrue();
|
||||
ProjectedMonitoredItem.SameAcquisition(sample, replay with { SourceVersion = 8 }).ShouldBeFalse();
|
||||
ProjectedMonitoredItem.SameAcquisition(sample, replay with { SourceVersion = null }).ShouldBeFalse();
|
||||
ProjectedMonitoredItem.SameAcquisition(sample, replay with { SourceVersion = 0 }).ShouldBeFalse();
|
||||
ProjectedMonitoredItem.SameAcquisition(sample, replay with { Proof = new Proof(new object()) }).ShouldBeFalse();
|
||||
ProjectedMonitoredItem.SameAcquisition(sample, replay with { ReceivedTimestamp = 124 }).ShouldBeTrue();
|
||||
ProjectedMonitoredItem.SameAcquisition(sample, replay with { OriginAgeBounds = new(TimeSpan.Zero, TimeSpan.FromSeconds(2)) }).ShouldBeTrue();
|
||||
ProjectedMonitoredItem.SameAcquisition(sample, replay with { Serving = replay.Serving with { ServingGeneration = 2 } }).ShouldBeFalse();
|
||||
ProjectedMonitoredItem.SameAcquisition(sample, replay with { Snapshot = replay.Snapshot with { ServerTimestampUtc = timestamp.AddTicks(1) } }).ShouldBeFalse();
|
||||
ProjectedMonitoredItem.SameAcquisition(sample, replay with { Snapshot = replay.Snapshot with { Value = new[] { 1, 3 } } }).ShouldBeFalse();
|
||||
}
|
||||
|
||||
private sealed class Proof(object identity) : IProjectedSamplePublicationProof
|
||||
{
|
||||
public bool IsValid => true;
|
||||
public object SourceIdentity => identity;
|
||||
public TimeProvider Clock => TimeProvider.System;
|
||||
public void Invalidate() { }
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
using System.Collections;
|
||||
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;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P11")]
|
||||
public sealed class GrpcDataAdversarialRecoveryTests
|
||||
{
|
||||
[Fact(Timeout = 30000)]
|
||||
public async Task Revocation_while_protobuf_values_are_encoding_fences_handoff_and_drains_charges()
|
||||
{
|
||||
var demand = new DeferredSubscriptionDemand(); demand.Accept();
|
||||
var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000);
|
||||
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
|
||||
LocalDataFixture? fixture = null;
|
||||
using (fixture = new LocalDataFixture(subscriptions: context => new LocalSubscriptionService(fixture!.Services, context,
|
||||
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
|
||||
{
|
||||
fixture.Publish(42);
|
||||
var baseline = fixture.Hub.Resources.RetainedBytes;
|
||||
await using var connection = fixture.Connection();
|
||||
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
using var sink = new HeldEncoderSink();
|
||||
var delivery = ((IDataSubscriptionTransport)subscription).RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
|
||||
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
|
||||
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
|
||||
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
try
|
||||
{
|
||||
await sink.EncoderEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
capacity.ActiveOperations.ShouldBe(1);
|
||||
fixture.Hub.Resources.RetainedBytes.ShouldBeGreaterThan(baseline);
|
||||
fixture.Activation.Begin("revoke-while-encoding");
|
||||
}
|
||||
finally { sink.Release(); }
|
||||
await sink.Encoded.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
await sink.Disposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
await delivery.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
await subscription.DisposeAsync();
|
||||
sink.ValueHandoffs.ShouldBe(0, "revoked bytes must never reach the transport write boundary");
|
||||
capacity.ActiveOperations.ShouldBe(0);
|
||||
fixture.Hub.Resources.RetainedBytes.ShouldBe(baseline);
|
||||
capacity.Snapshots.TryAcquire("peer", 1, out var next).ShouldBeTrue(); next!.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class HeldEncoderSink : IDataSubscriptionDeliverySink, IDisposable
|
||||
{
|
||||
private readonly ManualResetEventSlim _release = new();
|
||||
internal readonly TaskCompletionSource EncoderEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
internal readonly TaskCompletionSource Encoded = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
internal readonly TaskCompletionSource Disposed = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
internal int ValueHandoffs;
|
||||
public async ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes, CancellationToken cancellationToken)
|
||||
{
|
||||
if (frame is not DataSubscriptionValues values)
|
||||
return new Prepared(DataProtoMapper.EncodeControlOrAck(frame).ToByteArray(), false, this);
|
||||
// The production mapper is actively enumerating the real session's owned sample
|
||||
// when authority is revoked. The adapter holds only borrowed references; the session
|
||||
// remains the sole owner of the original frame and its resource leases.
|
||||
var borrowed = new DataSubscriptionValues(values.SubscriptionId, values.StreamEpoch, values.Sequence, values.IsSnapshot,
|
||||
new HeldItems(values.Items, EncoderEntered, _release));
|
||||
var bytes = await Task.Run(() => DataProtoMapper.EncodeValues(borrowed, true, subscriptionAgeReadiness: true).ToByteArray());
|
||||
Encoded.TrySetResult();
|
||||
return new Prepared(bytes, true, this);
|
||||
}
|
||||
public ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken)
|
||||
{
|
||||
var value = (Prepared)prepared;
|
||||
if (value.IsValue && value.Guard?.Invoke() == true) Interlocked.Increment(ref ValueHandoffs);
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
internal void Release() => _release.Set();
|
||||
public void Dispose() { _release.Set(); _release.Dispose(); }
|
||||
private sealed class Prepared(byte[] bytes, bool value, HeldEncoderSink owner) : IDataPreparedSubscriptionPublication
|
||||
{
|
||||
internal bool IsValue => value;
|
||||
internal Func<bool>? Guard;
|
||||
public long RetainedBytes => bytes.Length;
|
||||
public void SetPublicationGuard(Func<bool> guard) => Guard = guard;
|
||||
public void Dispose() { if (value) owner.Disposed.TrySetResult(); }
|
||||
}
|
||||
private sealed class HeldItems(IReadOnlyList<DataSubscriptionValue> items, TaskCompletionSource entered, ManualResetEventSlim release)
|
||||
: IReadOnlyList<DataSubscriptionValue>
|
||||
{
|
||||
public int Count => items.Count;
|
||||
public DataSubscriptionValue this[int index] => items[index];
|
||||
public IEnumerator<DataSubscriptionValue> GetEnumerator()
|
||||
{
|
||||
foreach (var item in items)
|
||||
{
|
||||
entered.TrySetResult();
|
||||
if (!release.Wait(TimeSpan.FromSeconds(10))) throw new TimeoutException("Encoder gate was not released.");
|
||||
yield return item;
|
||||
}
|
||||
}
|
||||
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
|
||||
}
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
using Akka.Actor;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P11")]
|
||||
public sealed class GrpcDataWorkloadAccountingTests : RuntimeActorTestBase
|
||||
{
|
||||
[Fact]
|
||||
public void Logical_sharing_counts_preserve_principal_and_pinned_target_boundaries()
|
||||
{
|
||||
var registry = new UpstreamDemandRegistry(8, 8);
|
||||
var key = new DemandSharingKey(HubTest.Ticket("driver", "tag").Key,
|
||||
new(DataTargetMode.Node, "cluster", "node-a"), DataConsistency.Primary, "principal", "export", 1, 1);
|
||||
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
|
||||
registry.TryAdd(key, settings, out var first).ShouldBeTrue();
|
||||
registry.TryAdd(key, settings, out var overlapping).ShouldBeTrue();
|
||||
registry.TryAdd(key with { PrincipalId = "other" }, settings, out var principal).ShouldBeTrue();
|
||||
registry.TryAdd(key with { Target = key.Target with { ExpectedNodeId = "node-b" } }, settings, out var pinned).ShouldBeTrue();
|
||||
registry.CaptureAccounting().ShouldBe((3, 4));
|
||||
first!.Dispose(); overlapping!.Dispose();
|
||||
registry.CaptureAccounting().ShouldBe((2, 2));
|
||||
principal!.Dispose(); pinned!.Dispose();
|
||||
registry.CaptureAccounting().ShouldBe((0, 0));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Snapshot_disposal_releases_snapshot_charge_while_steady_interest_remains_owned()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1);
|
||||
var ticket = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, ticket, 1, 42);
|
||||
hub.ProcessPending();
|
||||
var before = hub.CaptureAccounting();
|
||||
before.TrackedSources.ShouldBe(1);
|
||||
before.SnapshotItems.ShouldBe(0);
|
||||
before.InterestItems.ShouldBe(0);
|
||||
hub.TryCaptureInterestSnapshot([ticket], HubTest.Budget, CancellationToken.None, out var snapshot, out var interest).ShouldBeTrue();
|
||||
try
|
||||
{
|
||||
var during = hub.CaptureAccounting();
|
||||
during.SnapshotItems.ShouldBe(1); during.InterestItems.ShouldBe(1);
|
||||
during.RetainedBytes.ShouldBeGreaterThan(before.RetainedBytes);
|
||||
snapshot!.Dispose();
|
||||
var steady = hub.CaptureAccounting();
|
||||
steady.SnapshotItems.ShouldBe(0); steady.InterestItems.ShouldBe(1);
|
||||
steady.RetainedBytes.ShouldBeLessThan(during.RetainedBytes);
|
||||
}
|
||||
finally { snapshot!.Dispose(); interest!.Dispose(); }
|
||||
var after = hub.CaptureAccounting();
|
||||
after.SnapshotItems.ShouldBe(0); after.InterestItems.ShouldBe(0);
|
||||
after.RetainedBytes.ShouldBe(before.RetainedBytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Applied_physical_count_waits_for_ack_and_remains_until_cleanup_ack()
|
||||
{
|
||||
var probe = CreateTestProbe();
|
||||
var host = Sys.ActorOf(Props.Create(() => new OwnerProxy(probe.Ref)));
|
||||
using var source = new DriverHostSubscriptionDemandSource(host, new UpstreamDemandRegistry(8, 8), 8, 8,
|
||||
PresenceBudget, new SubscriptionAcquisitionCapacity(8));
|
||||
var view = new DataView(new("cluster", "urn:raw", "string", "tag"), DataRealm.Raw, null, 0, "subject");
|
||||
var authorized = new SubscriptionAuthorizedView(view, SourceKey.ForDriver("cluster", "driver", "tag", "node", "inc"),
|
||||
new("node", "inc", "Primary", 1, 1),
|
||||
new(view, "tag", "Variable", DataValueKind.Int32, -1, [], false, DataOperations.Subscribe, 1, "tag", null, false),
|
||||
"principal", "export", new(DataTargetMode.Node, "cluster", "node"), DataConsistency.Primary, () => true);
|
||||
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
|
||||
var token = TestContext.Current.CancellationToken;
|
||||
var pending = source.AcquireAsync(authorized, settings, token).AsTask();
|
||||
var apply = probe.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: token);
|
||||
var admitted = source.CaptureAccounting();
|
||||
admitted.LogicalInterests.ShouldBe(1); admitted.DesiredPhysicalReferences.ShouldBe(1);
|
||||
admitted.AppliedPhysicalReferences.ShouldBe(0);
|
||||
probe.Reply(new DriverInstanceActor.AcquisitionDemandApplied(apply.DesiredRevision, 7, settings.SamplingInterval, true));
|
||||
var lease = (await pending.WaitAsync(PresenceBudget, token)).Lease.ShouldNotBeNull();
|
||||
source.CaptureAccounting().AppliedPhysicalReferences.ShouldBe(1);
|
||||
lease.Dispose();
|
||||
var removal = probe.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: token);
|
||||
var retiring = source.CaptureAccounting();
|
||||
retiring.LogicalInterests.ShouldBe(0); retiring.DesiredPhysicalReferences.ShouldBe(0);
|
||||
retiring.AppliedPhysicalReferences.ShouldBe(1); retiring.RetiringDrivers.ShouldBe(1);
|
||||
probe.Reply(new DriverInstanceActor.AcquisitionDemandApplied(removal.DesiredRevision, 7, TimeSpan.Zero, true));
|
||||
await source.WaitForDriverIdleForTest("driver").WaitAsync(PresenceBudget, token);
|
||||
source.CaptureAccounting().AppliedPhysicalReferences.ShouldBe(0);
|
||||
}
|
||||
|
||||
private sealed class OwnerProxy : ReceiveActor
|
||||
{
|
||||
public OwnerProxy(IActorRef target)
|
||||
{
|
||||
Receive<DriverHostActor.RegisterAcquisitionOwner>(_ => Sender.Tell(new DriverHostActor.AcquisitionOwnerRegistered(true, 1)));
|
||||
Receive<DriverHostActor.OpenAcquisitionDemand>(message => Sender.Tell(new DriverHostActor.AcquisitionDemandOpened(true, message.RequestedKeyGeneration)));
|
||||
Receive<DriverHostActor.AbortOpenAcquisitionDemand>(_ => Sender.Tell(new DriverHostActor.AcquisitionOpenAborted(true)));
|
||||
Receive<DriverHostActor.ApplyAcquisitionDemand>(message => target.Forward(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user