133 lines
8.7 KiB
C#
133 lines
8.7 KiB
C#
using System.Buffers.Binary;
|
|
using System.Net;
|
|
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.Configuration.Entities;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
|
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
|
using BrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest;
|
|
using ReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
|
|
using ReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
|
{
|
|
[Theory(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
[InlineData(false, true)]
|
|
[InlineData(true, false)]
|
|
public async Task Deployed_sdk_write_honors_default_and_explicit_short_connection_deadlines(bool useShortTimeout, bool shouldDispatch)
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
var route = new DefaultBoundRecordingRoute();
|
|
DataWriteExecutor? executor = null;
|
|
using var origin = new LocalDataFixture(servingGeneration: 1,
|
|
targetSubscriptions: (_, _) => subscriptions, writes: _ => executor!);
|
|
peer = origin; route.View = origin.Raw;
|
|
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000,
|
|
TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
|
|
var capabilities = new DataCapabilitiesProvider("cluster", () => origin.Serving, () => true, limits);
|
|
var policy = new DataOperationPolicy(origin.Authority, new TriePermissionEvaluator(origin.Authority.Tries, origin.Clock), origin.Clock);
|
|
executor = new DataWriteExecutor(origin.Context, () => origin.Catalog, policy, capabilities, route,
|
|
new WriteOperationRegistry(origin.Serving.Incarnation, 16, 16_384, TimeSpan.FromMinutes(1), origin.Clock),
|
|
new WriteValueBudget(16_384), origin.Clock, DriverWriteBounds.Default);
|
|
var definition = new DataConnection
|
|
{
|
|
DataConnectionId = "link", ClusterId = "owner", Revision = 1, Enabled = true, ConsumerNodeIds = ["consumer"],
|
|
TargetMode = DataTargetMode.Node, ExpectedClusterId = "cluster", ExpectedNodeId = "node-a", Endpoints = ["https://fixture.test"],
|
|
SecretReference = "secret", SecretScopeClusterId = "owner", AllowedOperations = DataOperations.Write,
|
|
MaxMessageBytes = 1_000_000, MaxBatchItems = 2, MaxPageItems = 2, MaxStreams = 2,
|
|
MaxMonitoredItems = 8, MaxPendingBytes = 1_000_000
|
|
};
|
|
if (useShortTimeout) definition.TimeoutMilliseconds = 5000;
|
|
await using var deployment = new DataConnectionDeploymentRuntime("consumer", "owner", new DeployedWriteSecurity(origin, executor), new ImmediateFreshnessScope(), 4, origin.Clock);
|
|
deployment.Apply(new(1, "write-artifact", [definition]));
|
|
var deployed = new DeployedGrpcDataConnectionSource(deployment);
|
|
await WaitForDeployedFreshness(deployed, ct);
|
|
var source = new DeployedWriteSplitSource(origin, deployed);
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, resolver, applier, access, placements, anchor) =>
|
|
{
|
|
var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access,
|
|
new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8);
|
|
await using var lease = await discovery.ResolveAsync(Reference("map", DataRealm.Raw, origin.Raw.Address), ct);
|
|
lease.ShouldNotBeNull();
|
|
await subscriptions.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
var response = await ((SessionClient)session).WriteAsync(new RequestHeader { TimeoutHint = 30000 },
|
|
[new WriteValue { NodeId = anchor, AttributeId = Attributes.Value,
|
|
Value = new Opc.Ua.DataValue(new Variant(77), StatusCodes.Good) }], ct);
|
|
var status = response.Results.ToArray()!.ShouldHaveSingleItem();
|
|
if (shouldDispatch) status.ShouldBe(StatusCodes.Good);
|
|
else StatusCode.IsBad(status).ShouldBeTrue();
|
|
route.Dispatches.ShouldBe(shouldDispatch ? 1 : 0);
|
|
}, maxUnaryBytes: 1024 * 1024, allowWrite: true, connectionSource: source);
|
|
}
|
|
|
|
private sealed class DeployedWriteSecurity(LocalDataFixture origin, DataWriteExecutor executor) : IDataConnectionSecurityProvider
|
|
{
|
|
public event Action<string>? Changed { add { } remove { } }
|
|
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken ct) =>
|
|
ValueTask.FromResult<DataConnectionSecurity?>(new("v1", "ca", "key", () => new DeployedWriteHandler(origin, executor)));
|
|
}
|
|
private sealed class DeployedWriteHandler(LocalDataFixture origin, DataWriteExecutor executor) : HttpMessageHandler
|
|
{
|
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
|
{
|
|
IMessage message;
|
|
if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal))
|
|
{
|
|
await using var connection = origin.Connection();
|
|
var caps = await connection.GetCapabilitiesAsync(LocalDataFixture.Budget, ct);
|
|
message = DataProtoMapper.EncodeCapabilities(caps with { ResponseServingIdentity = true });
|
|
}
|
|
else
|
|
{
|
|
var bytes = await request.Content!.ReadAsByteArrayAsync(ct);
|
|
var batch = DataProtoMapper.DecodeWriteRequest(W.WriteRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray()), 100, 1_000_000);
|
|
try
|
|
{
|
|
var outcomes = await executor.WriteAsync(batch, ct);
|
|
var response = DataProtoMapper.EncodeWriteResponse(outcomes);
|
|
response.Serving = DataProtoMapper.EncodeServing(origin.Serving); message = response;
|
|
}
|
|
finally { foreach (var item in batch.Items) item.Value.Dispose(); }
|
|
}
|
|
var payload = message.ToByteArray(); var framed = new byte[payload.Length + 5];
|
|
BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); payload.CopyTo(framed, 5);
|
|
var responseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) };
|
|
responseMessage.Content.Headers.ContentType = new("application/grpc"); responseMessage.TrailingHeaders.Add("grpc-status", "0");
|
|
return responseMessage;
|
|
}
|
|
}
|
|
private sealed class DeployedWriteSplitSource(LocalDataFixture origin, DeployedGrpcDataConnectionSource deployed) : IGrpcDataAdapterConnectionSource
|
|
{
|
|
public async ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string id, CancellationToken ct)
|
|
{
|
|
var lease = await deployed.AcquireAsync(id, ct);
|
|
return lease is null ? null : new SplitLease(origin.Connection(), lease);
|
|
}
|
|
private sealed class SplitLease(IDataConnection local, IGrpcDataAdapterConnectionLease deployedLease) : IGrpcDataAdapterConnectionLease, IDataConnection
|
|
{
|
|
public IDataConnection Connection => this;
|
|
public CancellationToken CancellationToken => deployedLease.CancellationToken;
|
|
public DataTarget Target => deployedLease.Connection.Target;
|
|
public TimeProvider Clock => deployedLease.Connection.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) => deployedLease.Connection.WriteAsync(r, ct);
|
|
public Task<IDataSubscription> SubscribeAsync(CancellationToken ct) => local.SubscribeAsync(ct);
|
|
public async ValueTask DisposeAsync() { await local.DisposeAsync(); await deployedLease.DisposeAsync(); }
|
|
}
|
|
}
|
|
}
|