fix(grpc-data): maxAge=0 projected reads served from an awaited origin read; origin refusals are access denials; Write/CreateMonitoredItems renew lapsed leases (#938, #939, #940)

#938: OtOpcUaNodeManager implements IReadAsyncNodeManager. A projected Value read whose maxAge the
cache cannot satisfy (0 always: Part 4 "read the source"; ScadaBridge's DCL and the Client CLI send
0) is served from IProjectedDataAccess.ReadNowAsync in the same request — same unary admission,
authenticated freshness-checked read and cache publication as ScheduleRead, pumped through the
unary budget, at most 5 s / request deadline − 250 ms, no Lock, no blocked thread. A lapsed lease
is renewed first and read in the same request. Previously every maxAge=0 read answered
BadWaitingForInitialData forever.

#939: RemoteNamespaceResolver.RenewExactOutcomeAsync reports Renewed/Refused/Failed. Refused only
for the origin's verdict (PERMISSION_DENIED call, Denied item, Metadata not granted, operation not
granted / not writable) ⇒ BadUserAccessDenied, held 5 s per node+operation unsent; transport and
other failures stay retryable. HistoryRead follows it.

#940: RenewLapsed accepts Write (gated on the local write role) and Subscribe. WriteAsync awaits the
renewal (≤ 4 s, ≤ half the timeout hint) then dispatches, BadResourceUnavailable unsent otherwise.
CreateMonitoredItems awaits renewals once per request (ICreateMonitoredItemsAsyncNodeManager) and
classifies each projected item PER ITEM outside Lock (lapse ⇒ BadResourceUnavailable, refusal ⇒
BadUserAccessDenied) — a refusal thrown from the item manager used to fault the whole request.

Red/green: 15 wire tests in GrpcDataProjectedOriginAccessWireTests (12 red on the pre-fix source,
controls green both ways); 4 existing tests updated where the first read is now Good. Evidence:
docs/plans/evidence/grpc-data-ext/938-939-940-948.md.
This commit is contained in:
Joseph Doherty
2026-12-01 19:55:49 -05:00
parent 4fcabdf24a
commit 62d9504868
15 changed files with 1151 additions and 131 deletions
@@ -154,7 +154,9 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
var client = (SessionClient)session;
var first = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both,
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct);
first.Results[0].StatusCode.ShouldBe(StatusCodes.BadWaitingForInitialData);
// #938: the cold read is served from the origin read it triggers (same request), which also publishes the value.
StatusCode.IsGood(first.Results[0].StatusCode).ShouldBeTrue(first.Results[0].StatusCode.ToString());
first.Results[0].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
var update = await published.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
update.Snapshot.Value.ShouldBe(42);
var result = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both,
@@ -238,7 +238,8 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
var pending = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both,
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct);
pending.Results[0].StatusCode.ShouldBe(StatusCodes.BadWaitingForInitialData);
// #938: served by the origin read it triggers, which also publishes (and read-owns) the source.
StatusCode.IsGood(pending.Results[0].StatusCode).ShouldBeTrue(pending.Results[0].StatusCode.ToString());
mappedRead = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 42), ct);
mappedRead.Route.Serving.ShouldBe(originA.Serving);
var cached = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both,
@@ -58,10 +58,12 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
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.
// And again: every idle gap longer than the lease renews the same way — since #938 within the same request (the
// read awaits the renewal, then reads the origin), so the first read after the gap is already served.
origin.Clock.Advance(TimeSpan.FromSeconds(16));
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
var again = await ReadValue(client, anchor, ct);
StatusCode.IsGood(again.StatusCode).ShouldBeTrue(again.StatusCode.ToString());
again.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
@@ -0,0 +1,421 @@
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;
/// <summary>
/// #938 / #939 / #940 over the wire (real consumer SDK session + projection stack):
/// <list type="bullet">
/// <item>#938 — a projected Read whose <c>maxAge</c> the cache cannot satisfy (Part 4: <c>0</c> = read the source; the
/// Client CLI default and what ScadaBridge's DCL sends) is served from a bounded origin read in the SAME request.</item>
/// <item>#939 — a lapsed node whose renewal the ORIGIN refuses answers <c>BadUserAccessDenied</c> (held, unsent), while an
/// unreachable origin stays retryable.</item>
/// <item>#940 — Write and CreateMonitoredItems on a lapsed node renew it on demand instead of <c>BadUserAccessDenied</c>; a
/// real ACL denial stays <c>BadUserAccessDenied</c> and never reaches the origin.</item>
/// </list>
/// </summary>
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
private const int NoSubscribeGrant = 3; // Browse | Read
private const int NoWriteGrant = 7; // Browse | Read | Subscribe
private static async Task<Opc.Ua.DataValue> 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);
// 1 MiB unary budget = ONE read in flight at a time (each reserves it all), as in production by default.
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);
}, 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);
}
private static async Task<StatusCode> 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<StatusCode> 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;
/// <summary>
/// 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.
/// </summary>
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<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken)
{
if (connectionId != "link" || Unreachable) return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null);
lock (_gate) _inner ??= peer.Connection();
return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(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<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken);
public Task<DataBrowseBranch> BrowseAsync(DataBrowseRequest request, CancellationToken cancellationToken) => inner.BrowseAsync(request, cancellationToken);
public async Task<IReadOnlyList<DataItemResult<DataMetadata>>> 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<DataMetadata>(
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<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;
}
}
}
@@ -43,8 +43,12 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
[new ReadValueId { NodeId = node, AttributeId = Attributes.Value }], ct);
return result.Results[0];
}
// #938: the cold read is served from the origin read it triggers, in the same request — with the same fidelity.
var first = await ReadAsync();
first.StatusCode.ShouldBe(StatusCodes.BadWaitingForInitialData);
first.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
first.StatusCode.Code.ShouldBe(quality);
first.SourceTimestamp.ShouldBe((DateTimeUtc)sourceTime.UtcDateTime);
first.ServerTimestamp.ShouldBe((DateTimeUtc)serverTime.UtcDateTime);
var admitted = await published.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
admitted.SourceVersion.ShouldBe(version);
admitted.Snapshot.StatusCode.ShouldBe(quality);