206 lines
12 KiB
C#
206 lines
12 KiB
C#
using System.Runtime.CompilerServices;
|
|
using System.Threading.Channels;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
|
|
public sealed class GrpcDataAdapterLifecycleTests
|
|
{
|
|
private static readonly ServingIdentity Serving = new("remote", "boot", "Primary", 3, 4, 1);
|
|
private static readonly DataView View = new(new("remote-cluster", "urn:raw", "string", "Device/Speed"), DataRealm.Raw, null, 0, "Device/Speed");
|
|
private static readonly DataMetadata Metadata = new(View, "Speed", "Tag", DataValueKind.Int32, -1, [], true,
|
|
DataOperations.Read | DataOperations.Write | DataOperations.Subscribe, 3, null, null, false);
|
|
private static readonly string Ref = ProjectedDataIds.DependencyReference(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", View.Address));
|
|
private static readonly DataLimits Limits = new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5));
|
|
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
|
|
|
[Fact]
|
|
public async Task Unknown_remote_write_is_not_replayed_or_published_as_a_value()
|
|
{
|
|
var source = new FakeConnectionSource();
|
|
var routes = new FakeRoutes();
|
|
var adapter = new GrpcDataDriverAdapter("mapped-driver", "connection", source, routes);
|
|
var publications = 0;
|
|
adapter.OnDataChange += (_, _) => Interlocked.Increment(ref publications);
|
|
await adapter.InitializeAsync("{}", Ct);
|
|
var outcomes = await adapter.WriteWithOutcomesAsync([new WriteRequest(Ref, 42)], Ct);
|
|
outcomes.ShouldHaveSingleItem().State.ShouldBe(DataWriteState.OutcomeUnknown);
|
|
source.Connection.WriteCount.ShouldBe(1);
|
|
publications.ShouldBe(0);
|
|
await adapter.ShutdownAsync(Ct);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Stream_lease_is_retained_until_actual_stream_disposal_completes()
|
|
{
|
|
var source = new FakeConnectionSource();
|
|
var adapter = new GrpcDataDriverAdapter("mapped-driver", "connection", source, new FakeRoutes());
|
|
await adapter.InitializeAsync("{}", Ct);
|
|
#pragma warning disable OTOPCUA0001 // This test exercises the adapter lifetime directly.
|
|
var handle = await adapter.SubscribeAsync([Ref], TimeSpan.FromSeconds(1), Ct);
|
|
var closing = adapter.UnsubscribeAsync(handle, Ct);
|
|
#pragma warning restore OTOPCUA0001
|
|
try
|
|
{
|
|
await source.Connection.Stream.DisposeEntered.Task.WaitAsync(Ct);
|
|
source.LastLease.ShouldNotBeNull();
|
|
source.LastLease.Disposed.ShouldBeFalse();
|
|
}
|
|
finally { source.Connection.Stream.ReleaseDispose.TrySetResult(); }
|
|
await closing.WaitAsync(Ct);
|
|
source.LastLease!.Disposed.ShouldBeTrue();
|
|
await adapter.ShutdownAsync(Ct);
|
|
}
|
|
|
|
[Theory(Timeout = 15000)]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public async Task Initial_snapshot_is_atomic_and_typed_publication_keeps_origin_age(bool rejectPublication)
|
|
{
|
|
var source = new FakeConnectionSource();
|
|
source.Connection.Stream.HoldSnapshotEnd = true;
|
|
var publisher = new FakePublisher { Reject = rejectPublication };
|
|
var adapter = new GrpcDataDriverAdapter("mapped-driver", "connection", source, new FakeRoutes(), publisher);
|
|
await adapter.InitializeAsync("{}", Ct);
|
|
#pragma warning disable OTOPCUA0001 // Exercise the adapter's stream lifetime directly.
|
|
var handle = await adapter.SubscribeAsync([Ref], TimeSpan.FromSeconds(1), Ct);
|
|
#pragma warning restore OTOPCUA0001
|
|
try
|
|
{
|
|
await source.Connection.Stream.SnapshotValueConsumed.Task.WaitAsync(TimeSpan.FromSeconds(5), Ct);
|
|
publisher.Updates.ShouldBeEmpty();
|
|
source.Connection.Stream.FinishSnapshot();
|
|
await publisher.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), Ct);
|
|
var update = publisher.Updates.ShouldHaveSingleItem();
|
|
update.OriginAgeBounds.ShouldBe(new DataAgeBounds(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(4)));
|
|
if (rejectPublication)
|
|
SpinWait.SpinUntil(() => !update.SourceProof.IsValid, TimeSpan.FromSeconds(2)).ShouldBeTrue();
|
|
else update.SourceProof.IsValid.ShouldBeTrue();
|
|
update.Route.PublicationId.ShouldNotBe(Guid.Empty);
|
|
}
|
|
finally
|
|
{
|
|
source.Connection.Stream.ReleaseDispose.TrySetResult();
|
|
#pragma warning disable OTOPCUA0001 // Exercise the adapter's stream lifetime directly.
|
|
await adapter.UnsubscribeAsync(handle, Ct);
|
|
#pragma warning restore OTOPCUA0001
|
|
}
|
|
await adapter.ShutdownAsync(Ct);
|
|
}
|
|
|
|
private sealed class FakePublisher : IProjectedValuePublisher
|
|
{
|
|
public bool Reject { get; init; }
|
|
public List<ProjectedValueUpdate> Updates { get; } = [];
|
|
public TaskCompletionSource Published { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public bool TryBind(ProjectedValueRoute route) => true;
|
|
public bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates)
|
|
{ Updates.AddRange(updates); Published.TrySetResult(); return !Reject; }
|
|
public void Retire(ProjectedValueRoute route) { }
|
|
}
|
|
|
|
private sealed class FakeRoutes : IGrpcDataAdapterRouteSource
|
|
{
|
|
private readonly FakeLease _lease = new();
|
|
public bool TryResolve(string fullReference, out GrpcDataAdapterRoute? route)
|
|
{
|
|
route = fullReference == Ref ? new GrpcDataAdapterRoute(Ref, View, Metadata, Serving, _lease, 1) : null;
|
|
return route is not null;
|
|
}
|
|
}
|
|
private sealed class FakeLease : IDataAuthorizationLease
|
|
{
|
|
public bool IsValid => true;
|
|
public ServingIdentity Serving => GrpcDataAdapterLifecycleTests.Serving;
|
|
}
|
|
private sealed class FakeConnectionSource : IGrpcDataAdapterConnectionSource
|
|
{
|
|
public FakeConnection Connection { get; } = new();
|
|
public FakeConnectionLease? LastLease { get; private set; }
|
|
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken)
|
|
{
|
|
LastLease = new FakeConnectionLease(Connection);
|
|
return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(LastLease);
|
|
}
|
|
}
|
|
private sealed class FakeConnectionLease(FakeConnection connection) : IGrpcDataAdapterConnectionLease
|
|
{
|
|
public IDataConnection Connection => connection;
|
|
public CancellationToken CancellationToken => CancellationToken.None;
|
|
public bool Disposed { get; private set; }
|
|
public ValueTask DisposeAsync() { Disposed = true; return ValueTask.CompletedTask; }
|
|
}
|
|
private sealed class FakeConnection : IDataConnection
|
|
{
|
|
public int WriteCount { get; private set; }
|
|
public FakeSubscription Stream { get; } = new();
|
|
public DataTarget Target { get; } = new(DataTargetMode.Cluster, "remote-cluster", null);
|
|
public TimeProvider Clock => TimeProvider.System;
|
|
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) =>
|
|
Task.FromResult(new DataCapabilities(1, 2, Serving, DataReadiness.Ready,
|
|
DataOperations.Read | DataOperations.Write | DataOperations.Subscribe, new HashSet<DataValueKind> { DataValueKind.Int32 }, Limits, false, 0, "remote-cluster", true, true));
|
|
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
|
|
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
|
|
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
|
|
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken)
|
|
{
|
|
WriteCount++;
|
|
return Task.FromResult<IReadOnlyList<WriteItemResult>>(request.Items.Select(x => new WriteItemResult(x.CorrelationId,
|
|
new(DataWriteState.OutcomeUnknown, 0x800A0000u, "uncertain"))).ToArray());
|
|
}
|
|
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => Task.FromResult<IDataSubscription>(Stream);
|
|
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
|
}
|
|
private sealed class FakeSubscription : IDataSubscription, IDataSubscriptionProvenance
|
|
{
|
|
private readonly Channel<DataSubscriptionFrame> _frames = Channel.CreateUnbounded<DataSubscriptionFrame>();
|
|
private string? _subscriptionId;
|
|
private long _streamEpoch;
|
|
public bool HoldSnapshotEnd { get; set; }
|
|
public TaskCompletionSource SnapshotValueConsumed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public ServingIdentity Serving => GrpcDataAdapterLifecycleTests.Serving;
|
|
public TaskCompletionSource DisposeEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public TaskCompletionSource ReleaseDispose { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
|
|
{
|
|
if (command is OpenSubscription open)
|
|
{
|
|
_subscriptionId = open.SubscriptionId;
|
|
_streamEpoch = open.StreamEpoch;
|
|
var settings = open.Items[0].Settings;
|
|
_frames.Writer.TryWrite(new DataSubscriptionAck(open.SubscriptionId, open.StreamEpoch, 1, open.CommandId,
|
|
[new(open.Items[0].ClientItemId, DataItemStatus.Good, new(open.SubscriptionId, open.StreamEpoch, 1, 1), settings, null)]));
|
|
_frames.Writer.TryWrite(new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 2, DataStreamControlKind.SnapshotBegin, [], 3, 4, null));
|
|
if (HoldSnapshotEnd)
|
|
_frames.Writer.TryWrite(new DataSubscriptionValues(open.SubscriptionId, open.StreamEpoch, 3, true,
|
|
[new(new(open.SubscriptionId, open.StreamEpoch, 1, 1), new(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, 1),
|
|
new(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(4)), DataReadiness.Ready)]));
|
|
else _frames.Writer.TryWrite(new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 3, DataStreamControlKind.SnapshotEnd, [], 3, 4, null));
|
|
}
|
|
return Task.CompletedTask;
|
|
}
|
|
public void FinishSnapshot() => _frames.Writer.TryWrite(new DataSubscriptionControl(_subscriptionId!, _streamEpoch, 4,
|
|
DataStreamControlKind.SnapshotEnd, [], 3, 4, null));
|
|
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync([EnumeratorCancellation] CancellationToken cancellationToken)
|
|
{
|
|
await foreach (var frame in _frames.Reader.ReadAllAsync(cancellationToken))
|
|
{
|
|
yield return frame;
|
|
if (frame is DataSubscriptionValues) SnapshotValueConsumed.TrySetResult();
|
|
}
|
|
}
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
DisposeEntered.TrySetResult();
|
|
await ReleaseDispose.Task;
|
|
_frames.Writer.TryComplete();
|
|
}
|
|
}
|
|
}
|