195 lines
13 KiB
C#
195 lines
13 KiB
C#
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;
|
|
}
|
|
}
|
|
}
|
|
}
|