277 lines
18 KiB
C#
277 lines
18 KiB
C#
using Opc.Ua;
|
|
using Opc.Ua.Client;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
using DataBrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest;
|
|
using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
|
|
using DataReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
/// <summary>
|
|
/// #922 security-review round 1: on-demand renewal admission must not starve the unary budget (cold reads, writes, subscription
|
|
/// renewals), a batch of N lapsed nodes renews all N, a slow origin cannot pin SDK threads, and every refusal that is not a
|
|
/// lapse (a revoked lease, a revoked grant, a removed node) stays a refusal.
|
|
/// </summary>
|
|
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
|
{
|
|
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
|
public async Task A_read_batch_of_several_lapsed_nodes_renews_every_node_not_only_the_first()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1);
|
|
var connections = new GatedConnections(origin);
|
|
await WithComposedServer(origin, origin.Root, async (session, _, resolver, _, access, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
|
|
children.Length.ShouldBe(3);
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
|
var ids = children.Select(c => c.IdentifierAsString).ToArray();
|
|
ids.Count(id => resolver.TryResolveProjected(DataRealm.Raw, id, out var _1)).ShouldBe(0);
|
|
|
|
var read = await client.ReadAsync(new RequestHeader(), LongMaxAge, TimestampsToReturn.Both,
|
|
children.Select(c => new ReadValueId { NodeId = c, AttributeId = Attributes.Value }).ToArray(), ct);
|
|
read.Results.ToArray()!.ShouldAllBe(r => r.StatusCode.Code == StatusCodes.BadWaitingForInitialData.Code);
|
|
access.LapseRenewalsStartedForTests.ShouldBe(3, "every lapsed node in the batch is admitted for renewal");
|
|
for (var i = 0; i < 400 && !ids.All(id => resolver.TryResolveProjected(DataRealm.Raw, id, out _)); i++) await Task.Delay(25, ct);
|
|
ids.Count(id => resolver.TryResolveProjected(DataRealm.Raw, id, out var _2)).ShouldBe(3, "all three renewed, with no re-browse");
|
|
connections.BrowseCalls.ShouldBe(1);
|
|
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
|
public async Task A_history_batch_of_several_lapsed_nodes_renews_and_serves_every_node()
|
|
{
|
|
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2);
|
|
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port);
|
|
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
|
|
children.Length.ShouldBe(3);
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
|
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false,
|
|
children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken);
|
|
var results = response.Results.ToArray()!;
|
|
results.ShouldAllBe(r => StatusCode.IsGood(r.StatusCode), string.Join(", ", results.Select(r => r.StatusCode.ToString())));
|
|
results.ShouldAllBe(r => Values(r).Count == 3);
|
|
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin));
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
|
public async Task A_renewal_in_flight_does_not_crowd_out_a_cold_read_of_another_node()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1);
|
|
var connections = new GatedConnections(origin);
|
|
await WithComposedServer(origin, origin.Root, async (session, _, _, _, access, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
|
|
var (a, b) = (children[0], children[1]);
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
|
connections.HoldMetadataFor = a.IdentifierAsString;
|
|
(await ReadValue(client, a, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
|
|
await connections.Held.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); // A's renewal is now parked at the origin
|
|
|
|
// Re-browse renews B (and A) by page; B's cold read must still be dispatched while A's renewal is in flight.
|
|
await BrowseAll(client, anchor, 10);
|
|
var reads = connections.ReadCalls;
|
|
(await ReadValue(client, b, ct)).StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code);
|
|
for (var i = 0; i < 200 && connections.ReadCalls == reads; i++) await Task.Delay(25, ct);
|
|
connections.ReadCalls.ShouldBeGreaterThan(reads, "an on-demand renewal holds no unary capacity");
|
|
connections.Release();
|
|
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
|
public async Task An_invalidated_lease_is_a_refusal_not_a_lapse_and_never_reaches_the_origin()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
using var origin = new LocalDataFixture(servingGeneration: 1);
|
|
origin.Publish(42);
|
|
var connections = new GatedConnections(origin);
|
|
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, access, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
|
|
resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out var proof).ShouldBeTrue();
|
|
((BoundProjectionLease)proof!.Lease).Remote.Invalidate();
|
|
var metadata = connections.MetadataCalls;
|
|
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
|
|
access.LapseRenewalsStartedForTests.ShouldBe(0, "a revoked lease is never renewed");
|
|
connections.MetadataCalls.ShouldBe(metadata);
|
|
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
|
public async Task A_grant_revoked_while_the_renewal_is_at_the_origin_is_not_committed_and_the_read_is_denied()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
using var origin = new LocalDataFixture(servingGeneration: 1);
|
|
origin.Publish(42);
|
|
var connections = new GatedConnections(origin);
|
|
LocalCatalogCoordinator? coordinator = null;
|
|
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, access, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
|
connections.HoldMetadataFor = anchor.IdentifierAsString;
|
|
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
|
|
await connections.Held.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
|
|
Prepare(coordinator!, localPermissions: BrowseOnlyGrant); // the caller's Read grant is gone from now on
|
|
connections.Release();
|
|
for (var i = 0; i < 40; i++)
|
|
{
|
|
var value = await ReadValue(client, anchor, ct);
|
|
StatusCode.IsGood(value.StatusCode).ShouldBeFalse("nothing is served after the grant was revoked");
|
|
if (value.StatusCode.Code == StatusCodes.BadUserAccessDenied.Code) break;
|
|
await Task.Delay(50, ct);
|
|
}
|
|
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
|
|
resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse("the renewal never committed");
|
|
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale, onCoordinator: value => coordinator = value);
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
|
public async Task A_node_whose_mapping_is_removed_while_it_renews_is_not_revived()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
using var origin = new LocalDataFixture(servingGeneration: 1);
|
|
origin.Publish(42);
|
|
var connections = new GatedConnections(origin);
|
|
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
|
connections.HoldMetadataFor = anchor.IdentifierAsString;
|
|
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
|
|
await connections.Held.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
|
|
resolver.ApplyMappings([]); // the mapping goes away mid-renewal
|
|
connections.Release();
|
|
await Task.Delay(300, ct);
|
|
resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse();
|
|
resolver.TryResolveForRenewal(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse();
|
|
var value = await ReadValue(client, anchor, ct);
|
|
StatusCode.IsGood(value.StatusCode).ShouldBeFalse();
|
|
value.StatusCode.Code.ShouldNotBe(StatusCodes.BadWaitingForInitialData.Code, "a removed node is not a lapse");
|
|
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
|
public async Task Concurrent_history_reads_against_a_slow_origin_are_bounded_and_retryable_and_recover()
|
|
{
|
|
await using var originServer = await HistoryOrigin.StartAsync(7);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
|
|
var connections = new GatedConnections(origin);
|
|
OtOpcUaNodeManager? manager = null;
|
|
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
|
connections.HoldMetadataFor = anchor.IdentifierAsString; // the origin never answers the renewal until released
|
|
var clock = System.Diagnostics.Stopwatch.StartNew();
|
|
async Task<(Opc.Ua.HistoryReadResult Result, TimeSpan Took)> Timed()
|
|
{
|
|
var each = System.Diagnostics.Stopwatch.StartNew();
|
|
var result = await RawHistory(client, anchor, 3, default);
|
|
return (result, each.Elapsed);
|
|
}
|
|
var reads = Enumerable.Range(0, 24).Select(_ => Timed()).ToArray();
|
|
var all = Task.WhenAll(reads);
|
|
// Every waiter is bounded (a non-local history slot, then at most the lapse wait) — none is pinned until the origin
|
|
// answers, which it never does while held.
|
|
(await Task.WhenAny(all, Task.Delay(TimeSpan.FromSeconds(30), TestContext.Current.CancellationToken))).ShouldBe(all,
|
|
"every concurrent HistoryRead returned while the origin was still silent");
|
|
clock.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(30));
|
|
var statuses = all.Result.Select(r => r.Result.StatusCode.Code).ToArray();
|
|
// Waiters are capped by the non-local history slots: the reads that found none answer at once instead of each pinning
|
|
// an SDK thread for the whole lapse wait (the pre-review code made all 24 wait it out).
|
|
var slots = OriginHistoryPort.RemoteSlots(manager!.MaxConcurrentHistoryReadBatches);
|
|
all.Result.Count(r => r.Took < TimeSpan.FromSeconds(2.5)).ShouldBeGreaterThanOrEqualTo(24 - slots,
|
|
string.Join(", ", all.Result.Select(r => r.Took.TotalMilliseconds.ToString("0"))));
|
|
statuses.ShouldAllBe(code => code == StatusCodes.BadResourceUnavailable.Code, "granted + lapsed + silent origin ⇒ retryable");
|
|
originServer.Source.Calls.ShouldBe(0);
|
|
|
|
connections.Release();
|
|
Opc.Ua.HistoryReadResult? served = null;
|
|
for (var i = 0; i < 40; i++)
|
|
{
|
|
served = await RawHistory(client, anchor, 3, default);
|
|
if (StatusCode.IsGood(served.StatusCode)) break;
|
|
origin.Clock.Advance(ProjectedDataAccess.LapseRenewalBackoff + TimeSpan.FromMilliseconds(1));
|
|
await Task.Delay(50, TestContext.Current.CancellationToken);
|
|
}
|
|
StatusCode.IsGood(served!.StatusCode).ShouldBeTrue(served.StatusCode.ToString());
|
|
}, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (_, nm) => manager = nm);
|
|
}
|
|
|
|
/// <summary>One persistent origin connection whose metadata call for one node can be parked; counts browse/metadata/read calls.</summary>
|
|
private sealed class GatedConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
|
|
{
|
|
private IDataConnection? _inner;
|
|
private readonly object _gate = new();
|
|
private readonly object _route = new();
|
|
private int _browse, _metadata, _read;
|
|
private TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public int BrowseCalls => Volatile.Read(ref _browse);
|
|
public int MetadataCalls => Volatile.Read(ref _metadata);
|
|
public int ReadCalls => Volatile.Read(ref _read);
|
|
/// <summary>The projected local identifier whose origin metadata call is parked until <see cref="Release"/>.</summary>
|
|
public volatile string? HoldMetadataFor;
|
|
public TaskCompletionSource Held { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public void Release() { HoldMetadataFor = null; _release.TrySetResult(); }
|
|
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken)
|
|
{
|
|
if (connectionId != "link") return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null);
|
|
lock (_gate) _inner ??= peer.Connection();
|
|
return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Borrowed(new Gate(_inner, this), _route));
|
|
}
|
|
private sealed class Borrowed(IDataConnection connection, object route) : IGrpcDataAdapterConnectionLease
|
|
{
|
|
public IDataConnection Connection => connection;
|
|
public CancellationToken CancellationToken => CancellationToken.None;
|
|
public object? RouteIdentity => route;
|
|
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
|
}
|
|
private sealed class Gate(IDataConnection inner, GatedConnections owner) : IDataConnection, IDataHistoryService
|
|
{
|
|
public DataTarget Target => inner.Target;
|
|
public TimeProvider Clock => inner.Clock;
|
|
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken);
|
|
public Task<DataBrowseBranch> BrowseAsync(DataBrowseRequest request, CancellationToken cancellationToken)
|
|
{ Interlocked.Increment(ref owner._browse); return inner.BrowseAsync(request, cancellationToken); }
|
|
public async Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
|
|
{
|
|
Interlocked.Increment(ref owner._metadata);
|
|
if (owner.HoldMetadataFor is { } held && request.Views.Any(view =>
|
|
ProjectedDataIds.Identifier("map", view.Address) == held))
|
|
{
|
|
owner.Held.TrySetResult();
|
|
await owner._release.Task.WaitAsync(cancellationToken);
|
|
}
|
|
return await inner.GetMetadataAsync(request, cancellationToken);
|
|
}
|
|
public Task<IReadOnlyList<DataReadResult>> ReadAsync(DataReadRequest request, CancellationToken cancellationToken)
|
|
{ Interlocked.Increment(ref owner._read); return inner.ReadAsync(request, cancellationToken); }
|
|
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken);
|
|
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken);
|
|
public Task<IReadOnlyList<DataHistoryReadResult>> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) =>
|
|
((IDataHistoryService)inner).ReadAsync(request, cancellationToken);
|
|
public Task ReleaseAsync(IReadOnlyList<byte[]> continuations, CancellationToken cancellationToken) =>
|
|
((IDataHistoryService)inner).ReleaseAsync(continuations, cancellationToken);
|
|
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
|
}
|
|
}
|
|
}
|