251 lines
16 KiB
C#
251 lines
16 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.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 — a projected node idle longer than its <c>MetadataLeaseMilliseconds</c> (15 s here) is a LAPSE, not an
|
|
/// authorization failure: a value Read answers a retryable status and renews the lease on demand (no re-browse), a
|
|
/// HistoryRead renews it within the request's deadline and is served, and a re-browse served from a still-cached page
|
|
/// renews a lease that is past half its life. A real ACL denial stays <c>BadUserAccessDenied</c> after a lapse too, and
|
|
/// never reaches the origin.
|
|
/// </summary>
|
|
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
|
{
|
|
private const int BrowseOnlyGrant = 1;
|
|
// The fixture origin observes its one sample at t0 and never again, so the sample's ORIGIN age grows with the manual clock:
|
|
// a stale timeout and a client maxAge longer than the test's idle gaps keep that age out of what is under test (the lease).
|
|
private const int LongStale = 120_000;
|
|
private const double LongMaxAge = 120_000;
|
|
|
|
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
|
public async Task A_value_read_after_the_metadata_lease_lapses_is_retryable_and_renews_on_demand_without_a_browse()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
using var origin = new LocalDataFixture(servingGeneration: 1);
|
|
origin.Publish(42);
|
|
var connections = new CountingConnections(origin);
|
|
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
|
|
var browses = connections.BrowseCalls;
|
|
var metadata = connections.MetadataCalls;
|
|
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
|
var id = ProjectedDataIds.Identifier("map", origin.Raw.Address);
|
|
resolver.TryResolveProjected(DataRealm.Raw, id, out _).ShouldBeFalse("precondition: the lease has lapsed");
|
|
|
|
// A non-Value attribute of the lapsed node is not access-denied either (retryable while the lease renews).
|
|
var name = (await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither,
|
|
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.DisplayName }], ct)).Results[0];
|
|
name.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code);
|
|
var lapsed = await ReadValue(client, anchor, ct);
|
|
lapsed.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code, "a lease lapse is not an authorization failure");
|
|
// The attribute read above already started the renewal, which may have finished (and fetched the value) by now.
|
|
(StatusCode.IsGood(lapsed.StatusCode) || lapsed.StatusCode.Code == StatusCodes.BadWaitingForInitialData.Code ||
|
|
lapsed.StatusCode.Code == StatusCodes.BadResourceUnavailable.Code).ShouldBeTrue(lapsed.StatusCode.ToString());
|
|
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
|
|
resolver.TryResolveProjected(DataRealm.Raw, id, out _).ShouldBeTrue("the read renewed the node's authority");
|
|
connections.BrowseCalls.ShouldBe(browses, "the renewal is an exact metadata refresh, not a re-browse");
|
|
connections.MetadataCalls.ShouldBeGreaterThan(metadata, "renewed by an exact metadata call");
|
|
|
|
// And again: every idle gap longer than the lease renews the same way.
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
|
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
|
|
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
|
|
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
|
public async Task Without_the_local_read_grant_a_lapsed_value_read_is_still_BadUserAccessDenied_and_never_renews()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
using var origin = new LocalDataFixture(servingGeneration: 1);
|
|
origin.Publish(42);
|
|
var connections = new CountingConnections(origin);
|
|
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
// Positive control: before the lapse the same caller is refused for the ACL, not the lease.
|
|
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
|
var metadata = connections.MetadataCalls;
|
|
for (var i = 0; i < 3; i++)
|
|
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
|
|
await Task.Delay(200, ct);
|
|
connections.MetadataCalls.ShouldBe(metadata, "an unauthorized caller never triggers a renewal at the origin");
|
|
connections.ReadCalls.ShouldBe(0);
|
|
// Counted synchronously when a renewal is admitted, so this absence is not a race with a background task.
|
|
access.LapseRenewalsStartedForTests.ShouldBe(0);
|
|
}, connectionSource: connections, localPermissions: BrowseOnlyGrant);
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
|
public async Task A_history_read_after_the_metadata_lease_lapses_renews_within_the_request_and_is_served()
|
|
{
|
|
await using var originServer = await HistoryOrigin.StartAsync(7);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
|
|
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
StatusCode.IsGood((await RawHistory(client, anchor, 3, default)).StatusCode).ShouldBeTrue();
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
|
|
|
var lapsed = await RawHistory(client, anchor, 3, default);
|
|
lapsed.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code, "a lease lapse is not an authorization failure");
|
|
StatusCode.IsGood(lapsed.StatusCode).ShouldBeTrue(lapsed.StatusCode.ToString());
|
|
Values(lapsed).Count.ShouldBe(3);
|
|
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin));
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
|
public async Task A_lapsed_history_read_whose_renewal_cannot_reach_the_origin_is_retryable_not_denied_and_recovers()
|
|
{
|
|
await using var originServer = await HistoryOrigin.StartAsync(7);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
|
|
var connections = new DownableConnections(new PersistentConnections(origin));
|
|
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
|
connections.Down = true;
|
|
var calls = originServer.Source.Calls;
|
|
var down = await RawHistory(client, anchor, 3, default);
|
|
down.StatusCode.Code.ShouldBe(StatusCodes.BadResourceUnavailable.Code, "granted, lapsed, origin unreachable: retryable");
|
|
originServer.Source.Calls.ShouldBe(calls, "nothing is read under a lapsed lease");
|
|
|
|
connections.Down = false;
|
|
origin.Clock.Advance(ProjectedDataAccess.LapseRenewalBackoff + TimeSpan.FromMilliseconds(1)); // past the failure back-off
|
|
var recovered = await RawHistory(client, anchor, 3, default);
|
|
StatusCode.IsGood(recovered.StatusCode).ShouldBeTrue(recovered.StatusCode.ToString());
|
|
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
|
public async Task Without_the_local_history_grant_a_lapsed_history_read_is_still_BadUserAccessDenied_and_unsent()
|
|
{
|
|
await using var originServer = await HistoryOrigin.StartAsync(7);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
|
|
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
|
var result = await RawHistory(client, anchor, 3, default);
|
|
result.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
|
|
result.ContinuationPoint.IsEmpty.ShouldBeTrue();
|
|
originServer.Source.Calls.ShouldBe(0);
|
|
}, localPermissions: 7, allowHistory: true, connectionSource: new PersistentConnections(origin));
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
|
public async Task A_rebrowse_served_from_a_cached_page_past_half_its_lease_renews_the_lease()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
using var origin = new LocalDataFixture(servingGeneration: 1);
|
|
origin.Publish(42);
|
|
var connections = new CountingConnections(origin);
|
|
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
var id = ProjectedDataIds.Identifier("map", origin.Raw.Address);
|
|
await BrowseAll(client, anchor, 1);
|
|
var browses = connections.BrowseCalls;
|
|
|
|
// Inside the first half the cached page is served as is (no origin call).
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(5));
|
|
await BrowseAll(client, anchor, 1);
|
|
await Task.Delay(200, ct);
|
|
connections.BrowseCalls.ShouldBe(browses, "a fresh cached page is served without an origin call");
|
|
|
|
// Past half its life the cached page is still served, and the re-browse refreshes it in the background.
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(5));
|
|
await BrowseAll(client, anchor, 1);
|
|
for (var i = 0; i < 200 && connections.BrowseCalls == browses; i++) await Task.Delay(25, ct);
|
|
connections.BrowseCalls.ShouldBeGreaterThan(browses, "the re-browse refreshed the cached page");
|
|
|
|
// The original lease (t0 + 15 s) is gone; the renewed one still holds at t0 + 20 s.
|
|
ProjectedNodeProof? renewed = null;
|
|
for (var i = 0; i < 200; i++)
|
|
{
|
|
if (resolver.TryResolveProjected(DataRealm.Raw, id, out renewed) && renewed is not null &&
|
|
((BoundProjectionLease)renewed.Lease).Remaining > TimeSpan.FromSeconds(10)) break;
|
|
await Task.Delay(25, ct);
|
|
}
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(10));
|
|
resolver.TryResolveProjected(DataRealm.Raw, id, out _).ShouldBeTrue("the re-browse renewed the node's lease");
|
|
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
|
|
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
|
|
}
|
|
|
|
private static async Task<Opc.Ua.DataValue> ReadValue(SessionClient client, NodeId node, CancellationToken ct) =>
|
|
(await client.ReadAsync(new RequestHeader(), LongMaxAge, TimestampsToReturn.Both,
|
|
[new ReadValueId { NodeId = node, AttributeId = Attributes.Value }], ct)).Results[0];
|
|
|
|
private static async Task<object?> ReadUntilGood(SessionClient client, NodeId node, CancellationToken ct)
|
|
{
|
|
var deadline = DateTime.UtcNow.AddSeconds(10);
|
|
Opc.Ua.DataValue value;
|
|
do
|
|
{
|
|
value = await ReadValue(client, node, ct);
|
|
if (StatusCode.IsGood(value.StatusCode)) return value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy);
|
|
value.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code);
|
|
await Task.Delay(25, ct);
|
|
} while (DateTime.UtcNow < deadline);
|
|
throw new ShouldAssertException($"the projected read never became Good (last {value.StatusCode})");
|
|
}
|
|
|
|
/// <summary>A connection source that can be switched to "no connection" (an unreachable origin / undeployed route).</summary>
|
|
private sealed class DownableConnections(IGrpcDataAdapterConnectionSource inner) : IGrpcDataAdapterConnectionSource
|
|
{
|
|
public volatile bool Down;
|
|
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
|
|
Down ? ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null) : inner.AcquireAsync(connectionId, cancellationToken);
|
|
}
|
|
|
|
/// <summary>Like <c>FakeConnections</c>, counting browse, metadata and read calls separately.</summary>
|
|
private sealed class CountingConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
|
|
{
|
|
private int _browse, _metadata, _read;
|
|
public int BrowseCalls => Volatile.Read(ref _browse);
|
|
public int MetadataCalls => Volatile.Read(ref _metadata);
|
|
public int ReadCalls => Volatile.Read(ref _read);
|
|
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
|
|
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(connectionId == "link" ? new Lease(new Connection(peer.Connection(), this)) : null);
|
|
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
|
|
{
|
|
public IDataConnection Connection => connection;
|
|
public CancellationToken CancellationToken => CancellationToken.None;
|
|
public ValueTask DisposeAsync() => connection.DisposeAsync();
|
|
}
|
|
private sealed class Connection(IDataConnection inner, CountingConnections owner) : IDataConnection
|
|
{
|
|
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 Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
|
|
{ Interlocked.Increment(ref owner._metadata); return 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 ValueTask DisposeAsync() => inner.DisposeAsync();
|
|
}
|
|
}
|
|
}
|