fix(grpc-data): #922 review r1 — own renewal pool + queue, bounded HistoryRead wait, two-authority denial, per-op keys

This commit is contained in:
Joseph Doherty
2026-11-28 10:54:10 -05:00
parent b569d5c5dd
commit 7e924deda9
6 changed files with 351 additions and 24 deletions
@@ -8961,6 +8961,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
var vetoes = new ServiceResult?[nodesToProcess.Count];
var lapses = new ProjectedLapseOutcome?[nodesToProcess.Count];
var renewalTasks = new Task<bool>?[nodesToProcess.Count];
List<Task<bool>>? renewals = null;
var access = ProjectedDataAccess;
for (var i = 0; i < nodesToProcess.Count; i++)
@@ -8973,13 +8974,29 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
Task<bool>? renewal = null;
try { lapses[i] = access.RenewLapsed(handle.NodeId, identity, DataOperations.HistoryRead, out renewal); }
catch (Exception) { lapses[i] = ProjectedLapseOutcome.Denied; renewal = null; }
renewalTasks[i] = renewal;
if (renewal is not null) (renewals ??= []).Add(renewal);
}
if (renewals is not null)
{
// Block-bridged once per batch, like the projected history read itself; the SDK released Lock before dispatching.
try { Task.WhenAll(renewals).Wait(ProjectedLapseRenewalWait); }
catch (AggregateException) { }
// #922 review: the wait holds an SDK request thread, so it takes one of the SAME non-local history slots a projected
// read takes (never waiting for one — none free ⇒ the lapsed nodes are simply retryable), honours the request's
// cancellation, and is clearly longer than the renewal's own budget so a renewal that completes is never answered late.
var slots = GetNonLocalHistoryLimiter();
if (slots.Wait(0))
{
try
{
var wait = HistoryReadDeadline > TimeSpan.Zero && HistoryReadDeadline < ProjectedLapseRenewalWait
? HistoryReadDeadline : ProjectedLapseRenewalWait;
Task.WhenAll(renewals).Wait((int)wait.TotalMilliseconds,
context.OperationContext?.CancellationToken ?? CancellationToken.None);
}
catch (AggregateException) { }
catch (OperationCanceledException) { }
finally { slots.Release(); }
}
for (var i = 0; i < nodesToProcess.Count; i++)
if (lapses[i] is ProjectedLapseOutcome.Renewing) vetoes[i] = Veto(nodesToProcess[i]);
}
@@ -8995,6 +9012,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
continue;
}
// #922 review: the lapse classification and the veto are two authorities (DataOperationPolicy / DataPlaneAuthorizer).
// A renewal that SUCCEEDED and is still vetoed is a real refusal, never a retryable one.
if (lapses[i] is ProjectedLapseOutcome.Renewing && renewalTasks[i] is { IsCompletedSuccessfully: true, Result: true })
lapses[i] = ProjectedLapseOutcome.Denied;
if (lapses[i] is ProjectedLapseOutcome.Renewing or ProjectedLapseOutcome.Unavailable)
{
// Granted, but the lease could not be renewed in time (origin unreachable, capacity): retryable.
@@ -9013,8 +9034,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
return allowed;
}
/// <summary>#922: the longest a HistoryRead waits for the on-demand renewal of lapsed projected leases (one wait per batch).</summary>
internal static readonly TimeSpan ProjectedLapseRenewalWait = TimeSpan.FromSeconds(5);
/// <summary>
/// #922: the longest a HistoryRead waits for the on-demand renewal of lapsed projected leases (one wait per batch, capped by
/// <see cref="HistoryReadDeadline"/>) — longer than the renewal's own budget (3 s), so a completed renewal is always seen.
/// </summary>
internal static readonly TimeSpan ProjectedLapseRenewalWait = TimeSpan.FromSeconds(4);
/// <summary>#922: classifies (and, when it is a lapse, starts renewing) a refused projected node; total — a fault is Denied.</summary>
private static ProjectedLapseOutcome ClassifyProjectedLapse(IProjectedDataAccess access, NodeId nodeId,
@@ -13,6 +13,7 @@ internal sealed class BoundProjectionLease(MetadataAuthorityLease remote, Cancel
internal DataTarget? Target => target;
internal object? BindingIdentity => bindingIdentity;
internal TimeSpan Remaining => remote.Remaining;
internal MetadataAuthorityLease Remote => remote;
internal TimeSpan UsableDuration => remote.UsableDuration;
private bool RouteAlive => !route.IsCancellationRequested && (routeCurrent?.Invoke() ?? true);
internal bool LiveContext => RouteAlive && local.IsActive && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation);
@@ -22,6 +22,9 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
private readonly object _anchorGate = new();
private readonly ConcurrentDictionary<string, Installed> _installed = new(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<WorkKey, TaskCompletionSource> _inflight = new();
// #922 review: background refreshes of cached pages, keyed by the parent NODE (not caller / MaxResults), so varying the
// browse parameters cannot multiply origin browses of one parent.
private readonly ConcurrentDictionary<NodeId, byte> _refreshing = new();
private readonly record struct Failure(ProjectionPageStatus Status, long Until);
private readonly object _resultGate = new();
private readonly Dictionary<WorkKey, Failure> _failures = new();
@@ -194,7 +197,8 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
{
var now = _catalog.Clock.GetTimestamp();
foreach (var expired in _failures.Where(x => x.Value.Until <= now).Select(x => x.Key).ToArray()) _failures.Remove(expired);
if (refresh && (_failures.ContainsKey(key) || _inflight.ContainsKey(key))) return Empty(ProjectedBrowseReadiness.Pending);
if (refresh && (_failures.ContainsKey(key) || _inflight.ContainsKey(key) || !_refreshing.TryAdd(exactParent, 0)))
return Empty(ProjectedBrowseReadiness.Pending);
if (_failures.TryGetValue(key, out var failure))
return Empty(failure.Status switch
{
@@ -203,8 +207,12 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
_ => ProjectedBrowseReadiness.Unavailable
});
if (_inflight.ContainsKey(key)) return Empty(ProjectedBrowseReadiness.Pending);
if (_failures.Count + _pending >= _maxPending) return Empty(ProjectedBrowseReadiness.Unavailable);
if (!_inflight.TryAdd(key, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously))) return Empty(ProjectedBrowseReadiness.Pending);
if (_failures.Count + _pending >= _maxPending ||
!_inflight.TryAdd(key, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)))
{
if (refresh) _refreshing.TryRemove(exactParent, out _);
return Empty(_failures.Count + _pending >= _maxPending ? ProjectedBrowseReadiness.Unavailable : ProjectedBrowseReadiness.Pending);
}
_pending++;
}
_ = Task.Run(async () =>
@@ -217,6 +225,7 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
lock (_resultGate)
{
_inflight.TryRemove(key, out var completed);
if (refresh) _refreshing.TryRemove(exactParent, out _);
_pending--;
if (result != ProjectionPageStatus.Ready && !_stop.IsCancellationRequested)
{
@@ -201,13 +201,20 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireException); return false; }
}
// #922: at most one on-demand renewal per projected node; a failed one is not retried for a short back-off so a client
// polling a node whose origin is unreachable cannot turn every Read into a metadata call.
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier), Task<bool>> _lapseRenewals = new();
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier), long> _lapseRenewalBackoff = new();
// #922: at most one on-demand renewal per projected node AND operation (each requests its own bit at the origin); a failed
// one is not retried for a short back-off so a client polling a node whose origin is unreachable cannot turn every Read into
// a metadata call. Renewals never use the unary budget (that would starve cold reads, writes and subscription renewals):
// they queue — at most MaxQueuedLapseRenewals — for the resolver's own on-demand pool, so a batch of N lapsed nodes renews
// them all, a few at a time.
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), Task<bool>> _lapseRenewals = new();
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), long> _lapseRenewalBackoff = new();
private const int MaxLapseRenewalBackoffEntries = 4096;
internal const int MaxQueuedLapseRenewals = 64;
internal static readonly TimeSpan LapseRenewalBackoff = TimeSpan.FromMilliseconds(250);
internal static readonly TimeSpan LapseRenewalTimeout = TimeSpan.FromSeconds(5);
/// <summary>The whole on-demand renewal, pool wait included; clearly shorter than the longest a HistoryRead waits for it.</summary>
internal static readonly TimeSpan LapseRenewalTimeout = TimeSpan.FromSeconds(3);
/// <summary>One metadata item and its capability probe: never a multi-MiB unary reservation.</summary>
internal const long LapseRenewalBytes = 256 * 1024;
internal int LapseRenewalsStartedForTests => Volatile.Read(ref _lapseRenewalsStarted);
private int _lapseRenewalsStarted;
@@ -234,8 +241,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
// refused exactly as before, and never causes an origin call.
if (!_policy.AuthorizeMappedSubject(identity, Operation(operation), proof.Metadata.View, proof.Lease.Serving, proof.Subject, proof.Resolver))
return ProjectedLapseOutcome.Denied;
var key = (definition.Realm, definition.LocalIdentifier);
var budget = new DataBudget(LapseRenewalTimeout, 1, _limits.MaxUnaryBytes);
var key = (definition.Realm, definition.LocalIdentifier, operation);
var budget = new DataBudget(LapseRenewalTimeout, 1, Math.Min(LapseRenewalBytes, _limits.MaxUnaryBytes));
TaskCompletionSource<bool> started;
lock (_sync)
{
@@ -247,9 +254,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
if (now < until) return ProjectedLapseOutcome.Unavailable;
_lapseRenewalBackoff.Remove(key);
}
if (_unaryCount >= _limits.MaxUnaryOperations || budget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes)
return ProjectedLapseOutcome.Unavailable;
_unaryCount++; _unaryBytes += budget.MaxBytes;
if (_lapseRenewals.Count >= MaxQueuedLapseRenewals) return ProjectedLapseOutcome.Unavailable;
started = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_lapseRenewals.Add(key, started.Task);
}
@@ -263,7 +268,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
}
private async Task RunLapseRenewalAsync(RemoteNamespaceResolver resolver, IProjectedNamespacePageSink sink,
(DataRealm Realm, string LocalIdentifier) key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, NodeId nodeId,
(DataRealm Realm, string LocalIdentifier, DataOperations Operation) key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, NodeId nodeId,
RoleCarryingUserIdentity caller, DataCallerIdentity identity, DataOperations operation, DataBudget budget, TaskCompletionSource<bool> completion)
{
var renewed = false;
@@ -271,18 +276,17 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
{
renewed = await resolver.RenewExactAsync(proof, definition, nodeId, identity, null, sink, budget,
() => { lock (_sync) return !_disposed; }, CancellationToken.None, overlap: false,
authorizeAs: Operation(operation), required: operation).ConfigureAwait(false);
authorizeAs: Operation(operation), required: operation, onDemand: true).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException) { renewed = false; }
finally
{
lock (_sync)
{
_unaryCount--; _unaryBytes -= budget.MaxBytes;
_lapseRenewals.Remove(key);
if (!renewed && !_disposed)
{
if (_lapseRenewalBackoff.Count >= MaxLapseRenewalBackoffEntries) _lapseRenewalBackoff.Clear();
if (_lapseRenewalBackoff.Count >= MaxLapseRenewalBackoffEntries) EvictLapseBackoffLocked();
var delay = (long)(LapseRenewalBackoff.TotalSeconds * Clock.TimestampFrequency);
_lapseRenewalBackoff[key] = Clock.GetTimestamp() + Math.Max(1, delay);
}
@@ -303,6 +307,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
}
completion.TrySetResult(renewed);
}
// Full map (rare): drop the expired entries; if none expired, the one that expires first — never the whole map, which would
// let every node's back-off lapse at once.
private void EvictLapseBackoffLocked()
{
var now = Clock.GetTimestamp();
var expired = _lapseRenewalBackoff.Where(entry => entry.Value <= now).Select(entry => entry.Key).ToArray();
foreach (var key in expired) _lapseRenewalBackoff.Remove(key);
if (expired.Length == 0) _lapseRenewalBackoff.Remove(_lapseRenewalBackoff.MinBy(entry => entry.Value).Key);
}
/// <summary>The per-read byte budget the SDK Read path schedules a cold projected read with.</summary>
internal const long ProjectedReadBytes = 4 * 1024 * 1024;
internal bool TryAcquireConfigured(NodeId nodeId, ConfiguredProjectionCapability capability, out IProjectedDemandLease? demand)
@@ -22,6 +22,10 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
private readonly DataOperationPolicy _policy;
private readonly int _maxMappings;
private readonly SemaphoreSlim _fetchSlots;
// #922 review: on-demand renewals of lapsed nodes (a Read / HistoryRead) run on their OWN small pool, never on _fetchSlots,
// so a burst of them cannot crowd out browse pages or the subscription renewals that keep live items from lapsing.
private readonly SemaphoreSlim _onDemandSlots;
internal int OnDemandRenewalSlots { get; }
private readonly int _maximumWaiters;
private readonly Func<CancellationToken, Task>? _beforeFetch;
private int _waiterCount;
@@ -44,6 +48,8 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
_source = source ?? throw new ArgumentNullException(nameof(source)); _policy = policy ?? throw new ArgumentNullException(nameof(policy));
if (maxMappings <= 0 || maxConcurrentFetches <= 0) throw new ArgumentOutOfRangeException(nameof(maxMappings));
_maxMappings = maxMappings; _fetchSlots = new(maxConcurrentFetches, maxConcurrentFetches);
OnDemandRenewalSlots = Math.Max(1, maxConcurrentFetches / 2);
_onDemandSlots = new(OnDemandRenewalSlots, OnDemandRenewalSlots);
_maximumWaiters = checked(maxConcurrentFetches * 16);
_cache.Invalidated += OnInvalidated;
}
@@ -304,7 +310,8 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
internal async Task<bool> RenewExactAsync(ProjectedNodeProof previous, ProjectedVariableDefinition definition,
NodeId nodeId, DataCallerIdentity? caller, ConfiguredProjectionCapability? configured,
IProjectedNamespacePageSink sink, DataBudget budget, Func<bool> demandActive, CancellationToken cancellationToken, bool overlap = false,
OpcUaOperation authorizeAs = OpcUaOperation.CreateMonitoredItems, DataOperations required = DataOperations.Subscribe)
OpcUaOperation authorizeAs = OpcUaOperation.CreateMonitoredItems, DataOperations required = DataOperations.Subscribe,
bool onDemand = false)
{
// #922: a subscription renews for CreateMonitoredItems/Subscribe (the default); an on-demand renewal of a lapsed node
// renews for the operation the caller is performing (Read / HistoryRead) and requires exactly that bit at the origin.
@@ -329,7 +336,17 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
previous.Subject.Scope.Segments.Count < binding.LocalScope.Segments.Count ||
!previous.Subject.Scope.Segments.Take(binding.LocalScope.Segments.Count).SequenceEqual(binding.LocalScope.Segments, StringComparer.Ordinal) ||
!previous.Subject.LocalAncestry.SequenceEqual(binding.LocalAncestry, StringComparer.OrdinalIgnoreCase)) return false;
if (!await _fetchSlots.WaitAsync(0, cancellationToken).ConfigureAwait(false)) return false;
// A subscription renewal never queues (it retries on its own cadence); an on-demand renewal waits for its own pool within
// its budget, and the wait is charged to that budget.
var slots = onDemand ? _onDemandSlots : _fetchSlots;
var queued = System.Diagnostics.Stopwatch.GetTimestamp();
if (!await slots.WaitAsync(onDemand ? budget.Timeout : TimeSpan.Zero, cancellationToken).ConfigureAwait(false)) return false;
if (onDemand)
{
var left = budget.Timeout - System.Diagnostics.Stopwatch.GetElapsedTime(queued);
if (left <= TimeSpan.Zero) { slots.Release(); return false; }
budget = budget with { Timeout = left };
}
IGrpcDataAdapterConnectionLease? connection = null;
try
{
@@ -407,7 +424,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
{
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
catch (Exception) { }
finally { _fetchSlots.Release(); }
finally { slots.Release(); }
}
}
public void Dispose()
@@ -0,0 +1,263 @@
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 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);
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();
var reads = Enumerable.Range(0, 24).Select(_ => RawHistory(client, anchor, 3, default)).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.StatusCode.Code).ToArray();
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);
}
/// <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;
}
}
}