using RpcException = Grpc.Core.RpcException;
using RpcStatus = Grpc.Core.Status;
using RpcStatusCode = Grpc.Core.StatusCode;
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;
///
/// #938 / #939 / #940 over the wire (real consumer SDK session + projection stack):
///
/// - #938 — a projected Read whose maxAge the cache cannot satisfy (Part 4: 0 = read the source; the
/// Client CLI default and what ScadaBridge's DCL sends) is served from a bounded origin read in the SAME request.
/// - #939 — a lapsed node whose renewal the ORIGIN refuses answers BadUserAccessDenied (held, unsent), while an
/// unreachable origin stays retryable.
/// - #940 — Write and CreateMonitoredItems on a lapsed node renew it on demand instead of BadUserAccessDenied; a
/// real ACL denial stays BadUserAccessDenied and never reaches the origin.
///
///
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
private const int NoSubscribeGrant = 3; // Browse | Read
private const int NoWriteGrant = 7; // Browse | Read | Subscribe
private static async Task ReadAt(SessionClient client, NodeId node, double maxAge, CancellationToken ct) =>
(await client.ReadAsync(new RequestHeader(), maxAge, TimestampsToReturn.Both,
[new ReadValueId { NodeId = node, AttributeId = Attributes.Value }], ct)).Results[0];
// ---------------------------------------------------------------- #938
[Fact(Timeout = 90000), Trait("Issue", "938")]
public async Task A_max_age_zero_read_is_served_from_the_origin_in_the_same_request_every_time()
{
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, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var first = await ReadAt(client, anchor, 0, ct);
StatusCode.IsGood(first.StatusCode).ShouldBeTrue($"maxAge=0 must read the source, not answer {first.StatusCode}");
first.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
connections.ReadCalls.ShouldBe(1);
// maxAge = 0 is never served from the cache: every such read goes to the origin.
var second = await ReadAt(client, anchor, 0, ct);
StatusCode.IsGood(second.StatusCode).ShouldBeTrue(second.StatusCode.ToString());
second.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
connections.ReadCalls.ShouldBe(2);
// A maxAge the cache satisfies is served from it, with no origin call (the reads above warmed it).
// (The publication into the node's cache is asynchronous, so allow it to land.)
var fromCache = false;
for (var i = 0; i < 200 && !fromCache; i++)
{
var reads = connections.ReadCalls;
var cached = await ReadAt(client, anchor, LongMaxAge, ct);
cached.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
fromCache = connections.ReadCalls == reads;
if (!fromCache) await Task.Delay(10, ct);
}
fromCache.ShouldBeTrue("a maxAge the cache satisfies is served without an origin read");
}, connectionSource: connections);
}
[Fact(Timeout = 90000), Trait("Issue", "938")]
public async Task A_max_age_zero_batch_larger_than_the_unary_budget_is_pumped_and_fully_served()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(additionalRawNodes: 3, servingGeneration: 1);
origin.Publish(42);
var connections = new CountingConnections(origin);
// A unary budget of exactly one scalar read's reservation (#960) = ONE read in flight at a time.
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(4);
var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Both,
children.Select(c => new ReadValueId { NodeId = c, AttributeId = Attributes.Value }).ToArray(), ct);
var results = read.Results.ToArray()!;
results.ShouldAllBe(r => StatusCode.IsGood(r.StatusCode), string.Join(", ", results.Select(r => r.StatusCode.ToString())));
connections.ReadCalls.ShouldBe(4);
connections.MaxConcurrentReads.ShouldBe(1);
}, connectionSource: connections, maxUnaryBytes: ProjectedDataAccess.ProjectedEnvelopeBytes);
}
// ---------------------------------------------------------------- #960
[Fact(Timeout = 90000), Trait("Issue", "960")]
public async Task A_max_age_zero_batch_of_scalar_nodes_reads_the_origin_concurrently_within_the_default_budget()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(additionalRawNodes: 3, servingGeneration: 1);
origin.Publish(42);
var connections = new CountingConnections(origin) { ReadDelay = TimeSpan.FromMilliseconds(250) };
// The production default DataConnections:MaxPendingBytes (1 MiB). Before #960 each read reserved all of it, so the four
// origin reads ran one after another (~4 x 250 ms); the harness's operation limit (4) is now the only bound.
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(4);
var timer = System.Diagnostics.Stopwatch.StartNew();
var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Both,
children.Select(c => new ReadValueId { NodeId = c, AttributeId = Attributes.Value }).ToArray(), ct);
timer.Stop();
var results = read.Results.ToArray()!;
TestContext.Current.TestOutputHelper?.WriteLine(
$"#960: 4 maxAge=0 scalar reads, 250 ms origin each: {timer.ElapsedMilliseconds} ms, max {connections.MaxConcurrentReads} in flight");
results.ShouldAllBe(r => StatusCode.IsGood(r.StatusCode), string.Join(", ", results.Select(r => r.StatusCode.ToString())));
connections.ReadCalls.ShouldBe(4);
connections.MaxConcurrentReads.ShouldBe(4, "the four origin reads run concurrently, not one at a time");
}, connectionSource: connections, maxUnaryBytes: 1024 * 1024);
}
[Fact(Timeout = 90000), Trait("Issue", "938")]
public async Task A_max_age_zero_read_without_the_read_grant_is_denied_and_never_reaches_the_origin()
{
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, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
(await ReadAt(client, anchor, 0, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
connections.ReadCalls.ShouldBe(0);
}, connectionSource: connections, localPermissions: BrowseOnlyGrant);
}
[Fact(Timeout = 90000), Trait("Issue", "938")]
public async Task A_max_age_zero_read_of_a_lapsed_node_renews_and_is_served_in_one_request()
{
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);
origin.Clock.Advance(TimeSpan.FromSeconds(16));
resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse("precondition: the lease has lapsed");
var value = await ReadAt(client, anchor, 0, ct);
StatusCode.IsGood(value.StatusCode).ShouldBeTrue(value.StatusCode.ToString());
value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
connections.BrowseCalls.ShouldBe(1, "renewed by an exact metadata call, not a re-browse");
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
// ---------------------------------------------------------------- #939
public enum OriginRefusal { ItemDenied, OperationNotGranted, PermissionDeniedCall }
[Theory(Timeout = 90000), Trait("Issue", "939")]
[InlineData(OriginRefusal.ItemDenied)]
[InlineData(OriginRefusal.OperationNotGranted)]
[InlineData(OriginRefusal.PermissionDeniedCall)]
public async Task An_origin_refusing_the_renewal_of_a_lapsed_node_answers_access_denied_held_and_unsent(OriginRefusal refusal)
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(servingGeneration: 1);
origin.Publish(42);
var connections = new RefusingConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
StatusCode.IsGood((await ReadAt(client, anchor, LongMaxAge, ct)).StatusCode).ShouldBeTrue("precondition: readable");
origin.Clock.Advance(TimeSpan.FromSeconds(16));
connections.Refusal = refusal;
connections.Strip = DataOperations.Read;
(await ReadAt(client, anchor, LongMaxAge, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code,
"the origin's definitive refusal is an access denial, not a lapse to retry");
var metadata = connections.MetadataCalls;
for (var i = 0; i < 3; i++)
(await ReadAt(client, anchor, LongMaxAge, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
connections.MetadataCalls.ShouldBe(metadata, "a held refusal is answered without another origin call");
// The origin grants it again: once the hold expires the next read renews and is served.
connections.Refusal = null;
origin.Clock.Advance(ProjectedDataAccess.LapseRefusalHold + TimeSpan.FromMilliseconds(1));
var restored = await ReadAt(client, anchor, LongMaxAge, ct);
StatusCode.IsGood(restored.StatusCode).ShouldBeTrue(restored.StatusCode.ToString());
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
[Fact(Timeout = 90000), Trait("Issue", "939")]
public async Task An_unreachable_origin_for_a_lapsed_node_stays_retryable_not_denied()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(servingGeneration: 1);
origin.Publish(42);
var connections = new RefusingConnections(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.Unreachable = true; // a transport failure, not a verdict
for (var i = 0; i < 3; i++)
{
var value = await ReadAt(client, anchor, LongMaxAge, ct);
value.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code);
StatusCode.IsGood(value.StatusCode).ShouldBeFalse();
origin.Clock.Advance(ProjectedDataAccess.LapseRenewalBackoff + TimeSpan.FromMilliseconds(1));
}
connections.Unreachable = false;
StatusCode.IsGood((await ReadAt(client, anchor, LongMaxAge, ct)).StatusCode).ShouldBeTrue();
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
[Fact(Timeout = 90000), Trait("Issue", "939")]
public async Task An_origin_that_stops_granting_history_answers_a_lapsed_history_read_access_denied_unsent()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new RefusingConnections(origin);
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("precondition: history is served");
var calls = originServer.Source.Calls;
origin.Clock.Advance(TimeSpan.FromSeconds(16));
connections.Refusal = OriginRefusal.OperationNotGranted;
connections.Strip = DataOperations.HistoryRead;
var refused = await RawHistory(client, anchor, 3, default);
refused.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code, "the origin no longer grants HistoryRead");
originServer.Source.Calls.ShouldBe(calls, "nothing is read after the origin's refusal");
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
}
// ---------------------------------------------------------------- #940
[Fact(Timeout = 90000), Trait("Issue", "940")]
public async Task A_write_to_a_lapsed_node_renews_on_demand_and_is_dispatched()
{
var ct = TestContext.Current.CancellationToken;
var writes = new RecordingOriginWrites(DataWriteState.DriverConfirmedSuccess);
using var origin = new LocalDataFixture(servingGeneration: 1, writes: _ => writes);
origin.Publish(42);
var connections = new RefusingConnections(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));
resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse("precondition: the lease has lapsed");
(await Write(client, anchor, 77, ct)).ShouldBe(StatusCodes.Good, "a lease lapse is not an access denial");
writes.Calls.ShouldBe(1);
writes.Value.ShouldBe(77);
}, maxUnaryBytes: 1024 * 1024, allowWrite: true, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
[Fact(Timeout = 90000), Trait("Issue", "940")]
public async Task A_write_to_a_lapsed_node_without_the_write_grant_is_denied_and_never_reaches_the_origin()
{
var ct = TestContext.Current.CancellationToken;
var writes = new RecordingOriginWrites(DataWriteState.DriverConfirmedSuccess);
using var origin = new LocalDataFixture(servingGeneration: 1, writes: _ => writes);
var connections = new RefusingConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
(await Write(client, anchor, 77, ct)).ShouldBe(StatusCodes.BadUserAccessDenied, "positive control: denied before the lapse too");
origin.Clock.Advance(TimeSpan.FromSeconds(16));
var metadata = connections.MetadataCalls;
(await Write(client, anchor, 77, ct)).ShouldBe(StatusCodes.BadUserAccessDenied);
writes.Calls.ShouldBe(0);
connections.MetadataCalls.ShouldBe(metadata, "an unauthorized writer never triggers a renewal");
access.LapseRenewalsStartedForTests.ShouldBe(0);
}, maxUnaryBytes: 1024 * 1024, allowWrite: true, connectionSource: connections, localPermissions: NoWriteGrant);
}
[Fact(Timeout = 90000), Trait("Issue", "940")]
public async Task A_write_to_a_lapsed_node_whose_origin_is_unreachable_is_retryable_and_unsent()
{
var ct = TestContext.Current.CancellationToken;
var writes = new RecordingOriginWrites(DataWriteState.DriverConfirmedSuccess);
using var origin = new LocalDataFixture(servingGeneration: 1, writes: _ => writes);
var connections = new RefusingConnections(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.Unreachable = true;
(await Write(client, anchor, 77, ct)).ShouldBe(StatusCodes.BadResourceUnavailable);
writes.Calls.ShouldBe(0);
connections.Unreachable = false;
origin.Clock.Advance(ProjectedDataAccess.LapseRenewalBackoff + TimeSpan.FromMilliseconds(1));
(await Write(client, anchor, 78, ct)).ShouldBe(StatusCodes.Good);
writes.Calls.ShouldBe(1);
}, maxUnaryBytes: 1024 * 1024, allowWrite: true, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
[Fact(Timeout = 90000), Trait("Issue", "940")]
public async Task Creating_a_monitored_item_on_a_lapsed_node_renews_on_demand_instead_of_denying()
{
var ct = TestContext.Current.CancellationToken;
LocalDataFixture? peer = null;
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
peer = origin; subscriptions.SampleClock = origin.Clock;
var connections = new RefusingConnections(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));
resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse("precondition: the lease has lapsed");
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
(await CreateItem(client, sub, anchor, 1, ct)).ShouldBe(StatusCodes.Good, "a lease lapse is not an access denial");
resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeTrue("renewed on demand");
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
[Fact(Timeout = 90000), Trait("Issue", "940")]
public async Task Creating_a_monitored_item_on_a_lapsed_node_without_the_subscribe_grant_is_denied_and_unsent()
{
var ct = TestContext.Current.CancellationToken;
LocalDataFixture? peer = null;
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
peer = origin; subscriptions.SampleClock = origin.Clock;
var connections = new RefusingConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, 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 CreateItem(client, sub, anchor, 1, ct)).ShouldBe(StatusCodes.BadUserAccessDenied, "positive control: denied before the lapse");
origin.Clock.Advance(TimeSpan.FromSeconds(16));
var metadata = connections.MetadataCalls;
(await CreateItem(client, sub, anchor, 2, ct)).ShouldBe(StatusCodes.BadUserAccessDenied);
connections.MetadataCalls.ShouldBe(metadata);
access.LapseRenewalsStartedForTests.ShouldBe(0);
}, connectionSource: connections, localPermissions: NoSubscribeGrant);
}
[Fact(Timeout = 90000), Trait("Issue", "940")]
public async Task Creating_a_monitored_item_on_a_lapsed_node_whose_origin_is_unreachable_is_retryable()
{
var ct = TestContext.Current.CancellationToken;
LocalDataFixture? peer = null;
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
peer = origin; subscriptions.SampleClock = origin.Clock;
var connections = new RefusingConnections(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.Unreachable = true;
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
(await CreateItem(client, sub, anchor, 1, ct)).ShouldBe(StatusCodes.BadResourceUnavailable);
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
// ---------------------------------------------------------------- #961
private static MonitoredItemCreateRequest ItemRequest(NodeId node, uint handle) => new()
{
ItemToMonitor = new ReadValueId { NodeId = node, AttributeId = Attributes.Value },
MonitoringMode = MonitoringMode.Reporting,
RequestedParameters = new MonitoringParameters { ClientHandle = handle, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true },
};
[Fact(Timeout = 90000), Trait("Issue", "961")]
public async Task A_projected_item_refused_for_stream_capacity_at_create_fails_only_that_item()
{
var ct = TestContext.Current.CancellationToken;
LocalDataFixture? peer = null;
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
peer = origin; subscriptions.SampleClock = origin.Clock;
var connections = new RefusingConnections(origin);
// The harness allows 2 origin streams; one stream (cohort) is opened per publishing interval.
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
foreach (var interval in new double[] { 500, 1000 })
{
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), interval, 300, 1, 0, true, 0, ct)).SubscriptionId;
(await CreateItem(client, sub, anchor, 1, ct)).ShouldBe(StatusCodes.Good);
}
var third = (await client.CreateSubscriptionAsync(new RequestHeader(), 2000, 300, 1, 0, true, 0, ct)).SubscriptionId;
var response = await client.CreateMonitoredItemsAsync(new RequestHeader(), third, TimestampsToReturn.Both,
[ItemRequest(anchor, 1), ItemRequest(VariableIds.Server_ServerStatus_State, 2)], ct);
var results = response.Results.ToArray()!;
results[0].StatusCode.ShouldBe(StatusCodes.BadResourceUnavailable, "no origin stream can take it: retryable, for this item only");
results[1].StatusCode.ShouldBe(StatusCodes.Good, "the rest of the batch is created");
}, connectionSource: connections);
}
[Fact(Timeout = 90000), Trait("Issue", "961")]
public async Task A_projected_item_whose_lease_lapses_between_the_probe_and_the_create_is_retryable_for_that_item_only()
{
var ct = TestContext.Current.CancellationToken;
LocalDataFixture? peer = null;
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
peer = origin; subscriptions.SampleClock = origin.Clock;
var connections = new RefusingConnections(origin);
ZB.MOM.WW.OtOpcUa.OpcUaServer.OtOpcUaNodeManager? manager = null;
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var lapsed = 0;
// The authority changes after CreateMonitoredItems' per-item probe admitted the item, under the create's Lock.
manager.ShouldNotBeNull().BeforeProjectedItemAcquireForTests = _ =>
{
if (Interlocked.Exchange(ref lapsed, 1) == 0) origin.Clock.Advance(TimeSpan.FromSeconds(16));
};
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
var response = await client.CreateMonitoredItemsAsync(new RequestHeader(), sub, TimestampsToReturn.Both,
[ItemRequest(anchor, 1), ItemRequest(VariableIds.Server_ServerStatus_State, 2)], ct);
manager.BeforeProjectedItemAcquireForTests = null;
var results = response.Results.ToArray()!;
lapsed.ShouldBe(1, "precondition: the create ran after the probe");
results[0].StatusCode.ShouldBe(StatusCodes.BadResourceUnavailable, "a lapse the caller is granted is retryable, not an access denial");
results[1].StatusCode.ShouldBe(StatusCodes.Good, "the rest of the batch is created");
// ...and the retry succeeds once the on-demand renewal the classification started has committed.
var created = false;
for (var i = 0; i < 100 && !created; i++)
{
created = await CreateItem(client, sub, anchor, 3, ct) == StatusCodes.Good;
if (!created) await Task.Delay(50, ct);
}
created.ShouldBeTrue();
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale, onHistory: (_, m) => manager = m);
}
private static async Task Write(SessionClient client, NodeId node, int value, CancellationToken ct) =>
(await client.WriteAsync(new RequestHeader(),
[new WriteValue { NodeId = node, AttributeId = Attributes.Value, Value = new Opc.Ua.DataValue(new Variant(value), StatusCodes.Good) }], ct))
.Results.ToArray()!.ShouldHaveSingleItem();
private static async Task CreateItem(SessionClient client, uint subscription, NodeId node, uint handle, CancellationToken ct) =>
(await client.CreateMonitoredItemsAsync(new RequestHeader(), subscription, TimestampsToReturn.Both,
[new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = node, AttributeId = Attributes.Value },
MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters
{ ClientHandle = handle, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true } }], ct)).Results[0].StatusCode;
///
/// One persistent origin connection whose metadata answers can be turned into an origin refusal (#939) or whose
/// acquisition can fail as an unreachable origin would; counts metadata and read calls.
///
private sealed class RefusingConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
{
private IDataConnection? _inner;
private readonly object _gate = new();
private readonly object _route = new();
private int _metadata, _read;
public int MetadataCalls => Volatile.Read(ref _metadata);
public int ReadCalls => Volatile.Read(ref _read);
public volatile bool Unreachable;
private volatile object? _refusal;
public OriginRefusal? Refusal { get => (OriginRefusal?)_refusal; set => _refusal = value; }
public DataOperations Strip = DataOperations.Read;
public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken)
{
if (connectionId != "link" || Unreachable) return ValueTask.FromResult(null);
lock (_gate) _inner ??= peer.Connection();
return ValueTask.FromResult(new Borrowed(new Refusing(_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 Refusing(IDataConnection inner, RefusingConnections owner) : IDataConnection, IDataHistoryService
{
public DataTarget Target => inner.Target;
public TimeProvider Clock => inner.Clock;
public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken);
public Task BrowseAsync(DataBrowseRequest request, CancellationToken cancellationToken) => inner.BrowseAsync(request, cancellationToken);
public async Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
{
Interlocked.Increment(ref owner._metadata);
switch (owner.Refusal)
{
case OriginRefusal.PermissionDeniedCall:
// As GrpcDataConnection reports a call the origin answered PERMISSION_DENIED on every endpoint.
throw new InvalidOperationException("No ready authenticated data endpoint.",
new RpcException(new RpcStatus(RpcStatusCode.PermissionDenied, "Data operation denied.")));
case OriginRefusal.ItemDenied:
return request.Views.Select((_, i) => new DataItemResult(
i.ToString(System.Globalization.CultureInfo.InvariantCulture), DataItemStatus.Denied, null, null)).ToArray();
}
var results = await inner.GetMetadataAsync(request, cancellationToken);
return owner.Refusal == OriginRefusal.OperationNotGranted
? results.Select(x => x.Value is null ? x : x with { Value = x.Value with { AllowedOperations = x.Value.AllowedOperations & ~owner.Strip } }).ToArray()
: results;
}
public Task> ReadAsync(DataReadRequest request, CancellationToken cancellationToken)
{ Interlocked.Increment(ref owner._read); return inner.ReadAsync(request, cancellationToken); }
public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken);
public Task SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken);
public Task> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) =>
((IDataHistoryService)inner).ReadAsync(request, cancellationToken);
public Task ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) =>
((IDataHistoryService)inner).ReleaseAsync(continuations, cancellationToken);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
}