234 lines
14 KiB
C#
234 lines
14 KiB
C#
using System.Buffers.Binary;
|
|
using System.IO.Pipelines;
|
|
using System.Net;
|
|
using System.Threading.Channels;
|
|
using Google.Protobuf;
|
|
using Opc.Ua;
|
|
using Opc.Ua.Client;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
|
using ReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
|
|
using ReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
|
|
using BrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
|
{
|
|
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
public async Task Grpc_stream_snapshot_reaches_an_sdk_monitored_item_with_finite_age()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
var demand = new DeferredSubscriptionDemand(); demand.Accept();
|
|
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
|
|
var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1));
|
|
LocalDataFixture? peer = null;
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) =>
|
|
new LocalSubscriptionService(peer!.Services, context, target, demand, limits, capacity));
|
|
peer = origin; origin.Publish(42);
|
|
using var connections = new FreshnessWireConnections(origin);
|
|
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, sub, anchor, 1, 100, ct);
|
|
var update = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 42), ct);
|
|
update.OriginAgeBounds.Upper.ShouldNotBeNull();
|
|
update.SourceProof.IsValid.ShouldBeTrue("the stream must stay live through SDK publication");
|
|
Opc.Ua.DataValue notification;
|
|
do { notification = await PublishComposedValue(client, 1, ct); }
|
|
while (!StatusCode.IsGood(notification.StatusCode));
|
|
notification.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
|
|
}, onPublished: x => published.Writer.TryWrite(x), connectionSource: connections);
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
public async Task Subscribe_only_export_delivers_fresh_sdk_value_while_read_is_denied()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
var demand = new DeferredSubscriptionDemand(); demand.Accept();
|
|
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
|
|
LocalDataFixture? peer = null;
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, denyReadExport: true, targetSubscriptions: (context, target) =>
|
|
new LocalSubscriptionService(peer!.Services, context, target, demand,
|
|
new(16, 8, 100_000, TimeSpan.FromMinutes(1)), capacity));
|
|
peer = origin; origin.Publish(42);
|
|
await using (var direct = origin.Connection())
|
|
{
|
|
var reads = await direct.ReadAsync(new ReadRequest([new("read", origin.Raw, null)], LocalDataFixture.Budget), ct);
|
|
try { reads.ShouldHaveSingleItem().Status.ShouldBe(DataItemStatus.Denied); }
|
|
finally { foreach (var read in reads) read.Dispose(); }
|
|
}
|
|
using var connections = new FreshnessWireConnections(origin);
|
|
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
|
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, sub, anchor, 1, 100, ct);
|
|
var update = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 42), ct);
|
|
update.OriginAgeBounds.Upper.ShouldNotBeNull();
|
|
Opc.Ua.DataValue notification;
|
|
do { notification = await PublishComposedValue(client, 1, ct); }
|
|
while (!StatusCode.IsGood(notification.StatusCode));
|
|
notification.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
|
|
}, onPublished: x => published.Writer.TryWrite(x), connectionSource: connections);
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
public async Task Grpc_quiet_renewal_does_not_rejuvenate_expired_sample_and_new_version_recovers()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
var demand = new DeferredSubscriptionDemand(); demand.Accept();
|
|
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
|
|
var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1));
|
|
LocalDataFixture? peer = null;
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) =>
|
|
new LocalSubscriptionService(peer!.Services, context, target, demand, limits, capacity));
|
|
peer = origin; origin.Publish(42);
|
|
using var connections = new FreshnessWireConnections(origin);
|
|
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, sub, anchor, 1, 100, ct);
|
|
await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 42), ct);
|
|
(Opc.Ua.DataValue Value, uint Sequence) initial;
|
|
do { initial = await PublishComposedNotification(client, 1, ct); }
|
|
while (!StatusCode.IsGood(initial.Value.StatusCode));
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(3));
|
|
var replay = await client.RepublishAsync(new RequestHeader(), sub, initial.Sequence, ct);
|
|
var expired = ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value;
|
|
StatusCode.IsGood(expired.StatusCode).ShouldBeFalse("a new challenge cannot reset the age of an old sample");
|
|
HubTest.Publish(origin.Hub, origin.Ticket, 2, 43); origin.Hub.ProcessPending();
|
|
origin.Clock.Advance(TimeSpan.FromMilliseconds(200));
|
|
await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 43), ct);
|
|
Opc.Ua.DataValue fresh;
|
|
do { fresh = await PublishComposedValue(client, 1, ct); }
|
|
while (!StatusCode.IsGood(fresh.StatusCode));
|
|
fresh.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(43);
|
|
}, onPublished: x => published.Writer.TryWrite(x), connectionSource: connections, staleTimeoutMilliseconds: 2000);
|
|
}
|
|
|
|
// Catalog access stays local to keep this test focused on the real remote stream decoder.
|
|
private sealed class FreshnessWireConnections : IGrpcDataAdapterConnectionSource, IDisposable
|
|
{
|
|
private readonly LocalDataFixture _origin;
|
|
private readonly DataConnectionManager _manager = new("consumer", 1);
|
|
internal FreshnessWireConnections(LocalDataFixture origin)
|
|
{
|
|
_origin = origin;
|
|
_manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
|
}
|
|
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string id, CancellationToken ct)
|
|
{
|
|
if (id != "link") return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null);
|
|
var local = _origin.Connection();
|
|
var remote = new GrpcDataConnection("link", new(DataTargetMode.Node, "cluster", "node-a"),
|
|
[new Uri("https://fixture.test")], new FreshnessSecurity(_origin), _manager.Acquire("link"),
|
|
1_000_000, 1, _origin.Clock);
|
|
return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Lease(new SplitConnection(local, remote)));
|
|
}
|
|
public void Dispose() => _manager.Dispose();
|
|
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
|
|
{
|
|
public IDataConnection Connection => connection;
|
|
public CancellationToken CancellationToken => CancellationToken.None;
|
|
public ValueTask DisposeAsync() => connection.DisposeAsync();
|
|
}
|
|
private sealed class SplitConnection(IDataConnection local, IDataConnection remote) : IDataConnection
|
|
{
|
|
public DataTarget Target => remote.Target;
|
|
public TimeProvider Clock => remote.Clock;
|
|
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget b, CancellationToken ct) => local.GetCapabilitiesAsync(b, ct);
|
|
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest r, CancellationToken ct) => local.BrowseAsync(r, ct);
|
|
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest r, CancellationToken ct) => local.GetMetadataAsync(r, ct);
|
|
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest r, CancellationToken ct) => local.ReadAsync(r, ct);
|
|
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch r, CancellationToken ct) => local.WriteAsync(r, ct);
|
|
public Task<IDataSubscription> SubscribeAsync(CancellationToken ct) => remote.SubscribeAsync(ct);
|
|
public async ValueTask DisposeAsync() { await remote.DisposeAsync(); await local.DisposeAsync(); }
|
|
}
|
|
}
|
|
|
|
private sealed class FreshnessSecurity(LocalDataFixture origin, Action<DataSubscriptionSession>? onSession = null) : IDataConnectionSecurityProvider
|
|
{
|
|
public event Action<string>? Changed { add { } remove { } }
|
|
public ValueTask<DataConnectionSecurity?> ResolveAsync(string id, Uri endpoint, CancellationToken ct) =>
|
|
ValueTask.FromResult<DataConnectionSecurity?>(new("v1", "ca", "key", () => new FreshnessHandler(origin, onSession)));
|
|
}
|
|
|
|
private sealed class FreshnessHandler(LocalDataFixture origin, Action<DataSubscriptionSession>? onSession) : HttpMessageHandler
|
|
{
|
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
|
{
|
|
if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal))
|
|
{
|
|
await using var local = origin.Connection();
|
|
var capabilities = await local.GetCapabilitiesAsync(LocalDataFixture.Budget, ct);
|
|
return Response(new ByteArrayContent(Frame(DataProtoMapper.EncodeCapabilities(capabilities with
|
|
{ SubscriptionAgeReadiness = true, ResponseServingIdentity = true, SubscriptionFreshnessChallenges = true }))));
|
|
}
|
|
var incoming = new Pipe(); var outgoing = new Pipe();
|
|
_ = request.Content!.CopyToAsync(incoming.Writer.AsStream(), ct);
|
|
_ = ServeAsync(incoming.Reader.AsStream(), outgoing.Writer.AsStream(), ct);
|
|
return Response(new StreamContent(outgoing.Reader.AsStream()));
|
|
}
|
|
private async Task ServeAsync(Stream input, Stream output, CancellationToken ct)
|
|
{
|
|
try
|
|
{
|
|
await using var local = origin.Connection();
|
|
await using var stream = await local.SubscribeAsync(ct);
|
|
if (stream is DataSubscriptionSession session) onSession?.Invoke(session);
|
|
var reader = Task.Run(async () =>
|
|
{
|
|
while (true)
|
|
{
|
|
var prefix = new byte[5];
|
|
await input.ReadExactlyAsync(prefix, ct);
|
|
var bytes = new byte[BinaryPrimitives.ReadInt32BigEndian(prefix.AsSpan(1))];
|
|
await input.ReadExactlyAsync(bytes, ct);
|
|
await stream.SendAsync(DataProtoMapper.DecodeCommand(W.SubscriptionCommand.Parser.ParseFrom(bytes)), ct);
|
|
}
|
|
}, ct);
|
|
await foreach (var frame in stream.ReadAllAsync(ct))
|
|
{
|
|
try
|
|
{
|
|
var wire = frame is DataSubscriptionValues values
|
|
? DataProtoMapper.EncodeValues(values, false, true)
|
|
: DataProtoMapper.EncodeControlOrAck(frame);
|
|
wire.Serving = DataProtoMapper.EncodeServing(origin.Serving);
|
|
await output.WriteAsync(Frame(wire), ct); await output.FlushAsync(ct);
|
|
}
|
|
finally { (frame as IDisposable)?.Dispose(); }
|
|
}
|
|
await reader;
|
|
}
|
|
catch (Exception) { }
|
|
finally { await output.DisposeAsync(); }
|
|
}
|
|
private static byte[] Frame(IMessage message)
|
|
{
|
|
var payload = message.ToByteArray(); var bytes = new byte[payload.Length + 5];
|
|
BinaryPrimitives.WriteInt32BigEndian(bytes.AsSpan(1, 4), payload.Length);
|
|
payload.CopyTo(bytes, 5); return bytes;
|
|
}
|
|
private static HttpResponseMessage Response(HttpContent content)
|
|
{
|
|
var result = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = content };
|
|
content.Headers.ContentType = new("application/grpc"); result.TrailingHeaders.Add("grpc-status", "0"); return result;
|
|
}
|
|
}
|
|
}
|