Merge #938/#939/#940/#948: projected Read maxAge=0 serves a bounded async origin read; renewal carries refusal kind (PERMISSION_DENIED -> BadUserAccessDenied, cached 5 s); Write/CreateMonitoredItems renew a lapsed lease; no proof candidate for a re-delivered consumed acquisition

This commit is contained in:
Joseph Doherty
2026-12-01 19:56:38 -05:00
16 changed files with 1241 additions and 135 deletions
@@ -32,6 +32,39 @@ public enum ProjectedLapseOutcome
Unavailable,
}
/// <summary>#939: how an on-demand renewal of a lapsed projected lease ended.</summary>
public enum ProjectedRenewalResult
{
/// <summary>The lease was renewed and committed: retry the operation.</summary>
Renewed,
/// <summary>
/// The ORIGIN definitively refused it (the call answered <c>PERMISSION_DENIED</c>, the item <c>Denied</c>, or the metadata
/// no longer grants the operation): answer <c>BadUserAccessDenied</c>. Remembered briefly so a polling client does not
/// turn every request into an origin call.
/// </summary>
Refused,
/// <summary>Anything else (unreachable / unready origin, capacity, timeout, a changed shape or local fence): retryable.</summary>
Failed,
}
/// <summary>#938: how an immediate origin read of a projected node ended.</summary>
public enum ProjectedOriginReadStatus
{
/// <summary>The origin answered a fresh, authenticated sample: serve <see cref="ProjectedOriginRead.Value"/>.</summary>
Served,
/// <summary>No unary capacity right now (nothing was sent): the caller may retry once another read completes.</summary>
NotAdmitted,
/// <summary>Sent (or started), but nothing servable came back in time: unreachable, not ready, stale, cancelled or refused.</summary>
NoValue,
}
/// <summary>#938: the outcome of <see cref="IProjectedDataAccess.ReadNowAsync"/>.</summary>
public readonly record struct ProjectedOriginRead(ProjectedOriginReadStatus Status, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataValueSnapshot? Value)
{
public static ProjectedOriginRead NotAdmitted => new(ProjectedOriginReadStatus.NotAdmitted, null);
public static ProjectedOriginRead NoValue => new(ProjectedOriginReadStatus.NoValue, null);
}
/// <summary>Nonblocking local admission and bounded scheduling for projected data.</summary>
public interface IProjectedDataAccess
{
@@ -39,18 +72,30 @@ public interface IProjectedDataAccess
bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand);
/// <summary>On success owns the demand through physical completion; otherwise the caller retains it.</summary>
bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp);
/// <summary>
/// #938: reads the value from the origin NOW (a Part 4 <c>maxAge</c> the cache cannot satisfy, e.g. 0), within
/// <paramref name="budget"/> counted from <paramref name="requestStartedTimestamp"/>, admitted against the same unary
/// budget as <see cref="ScheduleRead"/>; the value is also published to the projection cache. Admission is decided
/// synchronously: a <see cref="ProjectedOriginReadStatus.NotAdmitted"/> answer comes back as an already-completed task,
/// so a caller can retry it once another read finishes. The caller keeps ownership of <paramref name="demand"/>.
/// </summary>
Task<ProjectedOriginRead> ReadNowAsync(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp,
CancellationToken cancellationToken) => Task.FromResult(ProjectedOriginRead.NotAdmitted);
Task<DataWriteOutcome> WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget,
long requestStartedTimestamp, CancellationToken cancellationToken);
bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval);
/// <summary>Requests a coalesced fresh authenticated snapshot without changing caller ownership.</summary>
bool RequestFreshSnapshot(IProjectedDemandLease demand) => false;
/// <summary>
/// #922: classifies a refused acquire of <paramref name="nodeId"/> for <paramref name="operation"/> (Read or HistoryRead) and,
/// when the only reason is a lapsed lease the caller would otherwise be granted, starts (or joins) ONE bounded asynchronous
/// exact renewal. Nonblocking and lock-free with respect to the caller: never call it, or wait on the task, under the
/// node-manager <c>Lock</c> — the renewal commits through the SDK sink, which takes it.
/// #922: classifies a refused acquire of <paramref name="nodeId"/> for <paramref name="operation"/> (Read, HistoryRead and,
/// since #940, Write and Subscribe) and, when the only reason is a lapsed lease the caller would otherwise be granted,
/// starts (or joins) ONE bounded asynchronous exact renewal. A recent definitive origin refusal (#939) is
/// <see cref="ProjectedLapseOutcome.Denied"/> without another origin call. Nonblocking and lock-free with respect to the
/// caller: never call it, or wait on the task, under the node-manager <c>Lock</c> — the renewal commits through the SDK
/// sink, which takes it.
/// </summary>
ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task<bool>? renewal)
ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation,
out Task<ProjectedRenewalResult>? renewal)
{
renewal = null;
return ProjectedLapseOutcome.Denied;
@@ -0,0 +1,334 @@
using System.Diagnostics;
using Opc.Ua;
using Opc.Ua.Server;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using DataValue = Opc.Ua.DataValue;
using DataValueSnapshot = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataValueSnapshot;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>
/// #938 / #940: the projected (gRPC data connection) Read and CreateMonitoredItems seams that must AWAIT the origin — an
/// immediate origin read for a <c>maxAge</c> the cache cannot satisfy, and the on-demand renewal of a lapsed metadata lease.
/// Both run in the SDK's async dispatch (<see cref="IReadAsyncNodeManager"/> / <see cref="ICreateMonitoredItemsAsyncNodeManager"/>,
/// forwarded by <c>AsyncNodeManagerAdapter</c>) with NO node-manager <c>Lock</c> held and no request thread blocked, then hand
/// the batch to the unchanged synchronous path, which skips what was served here and classifies the rest.
/// </summary>
public sealed partial class OtOpcUaNodeManager : IReadAsyncNodeManager, ICreateMonitoredItemsAsyncNodeManager
{
/// <summary>
/// #938: the longest one Read request waits for its projected origin work (lapse renewals, then the reads themselves),
/// further capped by the request's own deadline. Longer than a renewal's budget (3 s), so a renewal that completes is
/// followed by its read.
/// </summary>
internal static readonly TimeSpan ProjectedOriginReadWait = TimeSpan.FromSeconds(5);
/// <summary>#940: the longest a CreateMonitoredItems request waits for the renewal of lapsed projected items.</summary>
internal static readonly TimeSpan ProjectedSubscribeRenewalWait = TimeSpan.FromSeconds(4);
/// <summary>Kept back from the request deadline so the answer still reaches the client in time.</summary>
private static readonly TimeSpan ProjectedDeadlineMargin = TimeSpan.FromMilliseconds(250);
/// <inheritdoc />
async ValueTask IReadAsyncNodeManager.ReadAsync(OperationContext context, double maxAge, ArrayOf<ReadValueId> nodesToRead,
IList<DataValue> values, IList<ServiceResult> errors, CancellationToken cancellationToken)
{
if (SecurityFilteringActive && ProjectedDataAccess is { } access && IdentityOf(context) is { } identity)
{
try { await ReadProjectedFromOriginAsync(context, maxAge, nodesToRead, values, errors, access, identity, cancellationToken).ConfigureAwait(false); }
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Never fail the batch here: whatever was not served is answered by the synchronous path below.
}
}
Read(context, maxAge, nodesToRead, values, errors);
}
/// <summary>
/// Serves every projected Value read the cache cannot satisfy at <paramref name="maxAge"/> (Part 4: <c>0</c> = read the
/// source) from a bounded, awaited origin read. A lapsed lease is renewed first (#922 classification, unchanged), so an idle
/// node is served in the same request. Reads are admitted against the unary budget and pumped as capacity frees up; what
/// is not served by the deadline is left to (or answered like) the synchronous path: <c>BadWaitingForInitialData</c>.
/// </summary>
private async Task ReadProjectedFromOriginAsync(OperationContext context, double maxAge, ArrayOf<ReadValueId> nodesToRead,
IList<DataValue> values, IList<ServiceResult> errors, IProjectedDataAccess access, RoleCarryingUserIdentity identity,
CancellationToken cancellationToken)
{
var wait = Bound(context, ProjectedOriginReadWait);
if (wait <= TimeSpan.Zero) return;
var deadline = Stopwatch.GetTimestamp() + (long)(wait.TotalSeconds * Stopwatch.Frequency);
using var stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, context.CancellationToken);
var pending = new Queue<(int Index, IProjectedDemandLease Demand)>();
var running = new List<(int Index, IProjectedDemandLease Demand, Task<ProjectedOriginRead> Read)>();
List<(int Index, Task<ProjectedRenewalResult> Renewal)>? lapsed = null;
try
{
for (var ii = 0; ii < nodesToRead.Count; ii++)
{
var item = nodesToRead[ii];
if (item is null || item.Processed || item.AttributeId != Attributes.Value || !IsProjectedDescendant(item.NodeId)) continue;
if (TryAcquireProjectedRead(access, item.NodeId, identity, out var demand))
{
if (TryServeProjectedFromCache(item.NodeId, demand!, maxAge, out var cached))
{
demand!.Dispose();
values[ii] = cached; errors[ii] = null!; item.Processed = true;
continue;
}
pending.Enqueue((ii, demand!));
continue;
}
// #922 classification: only a lapse the caller would be granted starts a renewal; Denied / Unavailable are left to
// the synchronous path, which answers them exactly as before.
Task<ProjectedRenewalResult>? renewal = null;
ProjectedLapseOutcome lapse;
try { lapse = access.RenewLapsed(item.NodeId, identity, DataOperations.Read, out renewal); }
catch (Exception) { lapse = ProjectedLapseOutcome.Denied; }
if (lapse == ProjectedLapseOutcome.Renewing && renewal is not null) (lapsed ??= []).Add((ii, renewal));
}
if (lapsed is not null)
{
await WhenAllUntil(lapsed.Select(x => (Task)x.Renewal), deadline, stop.Token).ConfigureAwait(false);
foreach (var (index, renewal) in lapsed)
{
// Still renewing, failed or refused: the synchronous path joins / reads the outcome (BadWaitingForInitialData /
// BadResourceUnavailable / BadUserAccessDenied). Renewed: read it now, in this request.
if (renewal is not { IsCompletedSuccessfully: true, Result: ProjectedRenewalResult.Renewed }) continue;
if (TryAcquireProjectedRead(access, nodesToRead[index].NodeId, identity, out var demand)) pending.Enqueue((index, demand!));
}
}
if (pending.Count == 0) return;
while (pending.Count > 0 || running.Count > 0)
{
// Admit as many as the unary budget takes now; NotAdmitted is decided synchronously (a completed task).
while (pending.Count > 0 && !stop.IsCancellationRequested)
{
var remaining = Remaining(deadline);
if (remaining <= TimeSpan.Zero) break;
var (index, demand) = pending.Peek();
var read = access.ReadNowAsync(demand, new DataBudget(remaining, 1, ProjectedOriginReadBytes), access.Clock.GetTimestamp(), stop.Token);
if (read.IsCompletedSuccessfully && read.Result.Status == ProjectedOriginReadStatus.NotAdmitted) break;
pending.Dequeue();
running.Add((index, demand, read));
}
if (Remaining(deadline) <= TimeSpan.Zero || stop.IsCancellationRequested) break;
if (running.Count == 0)
{
// Capacity is held by other requests: poll it briefly, within the deadline.
await Task.Delay(TimeSpan.FromMilliseconds(10), stop.Token).ConfigureAwait(false);
continue;
}
var tasks = running.Select(x => (Task)x.Read).ToList();
var any = Task.WhenAny(tasks);
if (await Task.WhenAny(any, Task.Delay(Remaining(deadline), stop.Token)).ConfigureAwait(false) != any) break;
for (var k = running.Count - 1; k >= 0; k--)
{
var (index, demand, read) = running[k];
if (!read.IsCompleted) continue;
running.RemoveAt(k);
Settle(index, demand, read);
}
}
}
catch (OperationCanceledException) { }
finally
{
// Out of time: an admitted read that has not answered is answered "waiting" (it was sent; scheduling another would only
// duplicate it); a read never admitted is left to the synchronous path, which answers it from cache or schedules it.
foreach (var (index, demand, read) in running)
{
if (read.IsCompleted) { Settle(index, demand, read); continue; }
demand.Dispose(); // cancels the read
values[index] = new DataValue(Variant.Null, StatusCodes.BadWaitingForInitialData);
nodesToRead[index].Processed = true;
}
foreach (var (_, demand) in pending) demand.Dispose();
}
void Settle(int index, IProjectedDemandLease demand, Task<ProjectedOriginRead> read)
{
try
{
// The caller's authority is re-checked at serve time: a grant revoked (or a node retired) while the read was in
// flight serves nothing here and is classified by the synchronous path instead.
if (!demand.IsValid) return;
values[index] = read is { IsCompletedSuccessfully: true, Result: { Status: ProjectedOriginReadStatus.Served, Value: { } snapshot } }
? ProjectedDataValue(nodesToRead[index].NodeId, snapshot)
: new DataValue(Variant.Null, StatusCodes.BadWaitingForInitialData);
errors[index] = null!;
nodesToRead[index].Processed = true;
}
catch (Exception ex) when (ex is ArgumentException or InvalidCastException or OverflowException or InvalidOperationException)
{
values[index] = new DataValue(Variant.Null, StatusCodes.BadWaitingForInitialData);
errors[index] = null!;
nodesToRead[index].Processed = true;
}
finally { demand.Dispose(); }
}
}
/// <summary>The per-read byte reservation of an awaited origin read (as a scheduled read; narrowed to the adapter's limit).</summary>
private const long ProjectedOriginReadBytes = 4 * 1024 * 1024;
private static bool TryAcquireProjectedRead(IProjectedDataAccess access, NodeId nodeId, RoleCarryingUserIdentity identity,
out IProjectedDemandLease? demand)
{
demand = null;
try
{
if (access.TryAcquire(nodeId, identity, DataOperations.Read, out demand) && demand is { IsValid: true }) return true;
}
catch (Exception ex) when (ex is not OutOfMemoryException) { }
demand?.Dispose(); demand = null;
return false;
}
/// <summary>
/// The cached projected value of <paramref name="nodeId"/> when it is bound to <paramref name="demand"/>'s serving identity and
/// generation, still proven, and no older than <paramref name="maxAge"/> ms (Part 4: <c>maxAge = 0</c> is never served from cache).
/// </summary>
private bool TryServeProjectedFromCache(NodeId nodeId, IProjectedDemandLease demand, double maxAge, out DataValue value)
{
value = default;
if (!(maxAge > 0)) return false;
// Total: a cached value that cannot be served (shape conversion, a clock fault) is simply "not served from cache", so a
// caller holding a demand always keeps ownership of it.
try { return TryServeProjectedFromCacheCore(nodeId, demand, maxAge, out value); }
catch (Exception ex) when (ex is ArgumentException or InvalidCastException or OverflowException or InvalidOperationException)
{
value = default;
return false;
}
}
private bool TryServeProjectedFromCacheCore(NodeId nodeId, IProjectedDemandLease demand, double maxAge, out DataValue value)
{
value = default;
ProjectedValueWrite? cached;
var byteArray = false;
lock (Lock)
{
_projectedSamples.TryGetValue(nodeId, out cached);
if (_projectedVariables.TryGetValue(nodeId, out var mapped))
byteArray = mapped.Metadata.ValueKind == DataValueKind.Array && mapped.Metadata.ArrayElementKind == DataValueKind.UInt8;
}
if (cached is null || !cached.Proof.IsValid || !demand.IsValid || cached.Serving != demand.Serving ||
cached.ProjectionGeneration != demand.ProjectionGeneration ||
!cached.OriginAgeBounds.Advance(cached.Proof.Clock.GetElapsedTime(cached.ReceivedTimestamp, cached.Proof.Clock.GetTimestamp()))
.IsFresh(TimeSpan.FromMilliseconds(Math.Min(maxAge, TimeSpan.MaxValue.TotalMilliseconds)))) return false;
var candidate = new DataValue(SdkValueBoundary.FromClr(cached.Snapshot.Value, byteArray), cached.Snapshot.StatusCode,
(DateTimeUtc)(cached.Snapshot.SourceTimestampUtc ?? DateTime.MinValue),
(DateTimeUtc)(cached.Snapshot.ServerTimestampUtc ?? DateTime.MinValue));
if (!cached.Proof.IsValid || !demand.IsValid) return false;
value = candidate;
return true;
}
/// <summary>An origin sample read for this request, as the SDK DataValue the projected node would carry.</summary>
private DataValue ProjectedDataValue(NodeId nodeId, DataValueSnapshot snapshot)
{
var byteArray = false;
lock (Lock)
if (_projectedVariables.TryGetValue(nodeId, out var mapped))
byteArray = mapped.Metadata.ValueKind == DataValueKind.Array && mapped.Metadata.ArrayElementKind == DataValueKind.UInt8;
return new DataValue(SdkValueBoundary.FromClr(snapshot.Value, byteArray), snapshot.StatusCode,
(DateTimeUtc)(snapshot.SourceTimestampUtc ?? DateTime.MinValue), (DateTimeUtc)(snapshot.ServerTimestampUtc ?? DateTime.MinValue));
}
/// <inheritdoc />
async ValueTask ICreateMonitoredItemsAsyncNodeManager.CreateMonitoredItemsAsync(OperationContext context, uint subscriptionId,
double publishingInterval, TimestampsToReturn timestampsToReturn, ArrayOf<MonitoredItemCreateRequest> itemsToCreate,
IList<ServiceResult> errors, IList<MonitoringFilterResult> filterErrors, IList<IMonitoredItem> monitoredItems, bool createDurable,
MonitoredItemIdFactory monitoredItemIdFactory, CancellationToken cancellationToken)
{
if (SecurityFilteringActive && ProjectedDataAccess is { } access && IdentityOf(context) is { } identity)
{
try { await RenewLapsedProjectedItemsAsync(context, itemsToCreate, access, identity, cancellationToken).ConfigureAwait(false); }
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Never fail the batch here: the synchronous create classifies every projected item itself.
}
}
CreateMonitoredItems(context, subscriptionId, publishingInterval, timestampsToReturn, itemsToCreate, errors, filterErrors,
monitoredItems, createDurable, monitoredItemIdFactory);
}
/// <summary>
/// #940: starts (or joins) the on-demand renewal of every projected Value item whose lease lapsed and that the caller would be
/// granted Subscribe on, and waits for them (once per request, bounded, no <c>Lock</c> held), so the synchronous create that
/// follows acquires them. Anything not renewed by then is classified per item by <see cref="ProjectedSubscribeRefusal"/>.
/// </summary>
private async Task RenewLapsedProjectedItemsAsync(OperationContext context, ArrayOf<MonitoredItemCreateRequest> itemsToCreate,
IProjectedDataAccess access, RoleCarryingUserIdentity identity, CancellationToken cancellationToken)
{
List<Task<ProjectedRenewalResult>>? renewing = null;
for (var ii = 0; ii < itemsToCreate.Count; ii++)
{
var item = itemsToCreate[ii];
if (item is null || item.Processed || item.ItemToMonitor?.AttributeId != Attributes.Value ||
!IsProjectedDescendant(item.ItemToMonitor.NodeId)) continue;
Task<ProjectedRenewalResult>? renewal = null;
ProjectedLapseOutcome lapse;
try { lapse = access.RenewLapsed(item.ItemToMonitor.NodeId, identity, DataOperations.Subscribe, out renewal); }
catch (Exception) { lapse = ProjectedLapseOutcome.Denied; }
if (lapse == ProjectedLapseOutcome.Renewing && renewal is not null) (renewing ??= []).Add(renewal);
}
if (renewing is null) return;
var wait = Bound(context, ProjectedSubscribeRenewalWait);
if (wait <= TimeSpan.Zero) return;
using var stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, context.CancellationToken);
try
{
await WhenAllUntil(renewing, Stopwatch.GetTimestamp() + (long)(wait.TotalSeconds * Stopwatch.Frequency), stop.Token)
.ConfigureAwait(false);
}
catch (OperationCanceledException) { }
}
/// <summary>
/// #940: why a projected Value monitored item cannot be created right now, or null when it can be acquired. A lapse the caller
/// is granted (renewing, back-off, capacity) is <c>BadResourceUnavailable</c> — retryable, as for Read; a real ACL denial,
/// a revoked/removed node and a held origin refusal (#939) are <c>BadUserAccessDenied</c>. Never call under <c>Lock</c>.
/// </summary>
private static StatusCode? ProjectedSubscribeRefusal(IProjectedDataAccess access, NodeId nodeId, RoleCarryingUserIdentity identity)
{
IProjectedDemandLease? probe = null;
try
{
if (access.TryAcquire(nodeId, identity, DataOperations.Subscribe, out probe) && probe is { IsValid: true }) return null;
}
catch (Exception ex) when (ex is not OutOfMemoryException) { }
finally { probe?.Dispose(); }
ProjectedLapseOutcome lapse;
try { lapse = access.RenewLapsed(nodeId, identity, DataOperations.Subscribe, out _); }
catch (Exception) { lapse = ProjectedLapseOutcome.Denied; }
return lapse == ProjectedLapseOutcome.Denied ? StatusCodes.BadUserAccessDenied : StatusCodes.BadResourceUnavailable;
}
private static TimeSpan Bound(OperationContext context, TimeSpan cap)
{
var deadline = context.OperationDeadline;
if (deadline == DateTime.MaxValue || deadline <= DateTime.MinValue) return cap;
var left = deadline - DateTime.UtcNow - ProjectedDeadlineMargin;
return left < cap ? left : cap;
}
private static TimeSpan Remaining(long deadline)
{
var ticks = deadline - Stopwatch.GetTimestamp();
return ticks <= 0 ? TimeSpan.Zero : TimeSpan.FromSeconds((double)ticks / Stopwatch.Frequency);
}
private static async Task WhenAllUntil(IEnumerable<Task> tasks, long deadline, CancellationToken cancellationToken)
{
var all = Task.WhenAll(tasks);
var remaining = Remaining(deadline);
if (remaining <= TimeSpan.Zero) return;
try { await all.WaitAsync(remaining, cancellationToken).ConfigureAwait(false); }
catch (TimeoutException) { }
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException) { }
}
}
@@ -6351,24 +6351,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
? StatusCodes.BadWaitingForInitialData : StatusCodes.BadResourceUnavailable);
continue;
}
ProjectedValueWrite? cached;
var byteArray = false;
lock (Lock)
{
_projectedSamples.TryGetValue(projected.NodeId, out cached);
if (_projectedVariables.TryGetValue(projected.NodeId, out var mapped))
byteArray = mapped.Metadata.ValueKind == DataValueKind.Array && mapped.Metadata.ArrayElementKind == DataValueKind.UInt8;
}
if (cached is not null && cached.Proof.IsValid && demand.IsValid && cached.Serving == demand.Serving &&
cached.ProjectionGeneration == demand.ProjectionGeneration && maxAge > 0 &&
cached.OriginAgeBounds.Advance(cached.Proof.Clock.GetElapsedTime(cached.ReceivedTimestamp,
cached.Proof.Clock.GetTimestamp())).IsFresh(TimeSpan.FromMilliseconds(Math.Min(maxAge, TimeSpan.MaxValue.TotalMilliseconds))))
{
var value = new DataValue(SdkValueBoundary.FromClr(cached.Snapshot.Value, byteArray), cached.Snapshot.StatusCode,
(DateTimeUtc)(cached.Snapshot.SourceTimestampUtc ?? DateTime.MinValue),
(DateTimeUtc)(cached.Snapshot.ServerTimestampUtc ?? DateTime.MinValue));
if (cached.Proof.IsValid && demand.IsValid) { values[ii] = value; continue; }
}
if (TryServeProjectedFromCache(projected.NodeId, demand, maxAge, out var cachedValue)) { values[ii] = cachedValue; continue; }
var started = access.Clock.GetTimestamp();
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
if (access.ScheduleRead(demand, budget, started)) demand = null; // ownership transfers only on admission
@@ -6585,8 +6568,20 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
var item = itemsToCreate[ii];
var target = item.ItemToMonitor?.NodeId;
if (item.Processed || !OwnsNamespace(target)) continue;
if (target is { } projected && IsProjectedDescendant(projected) && identity is not null && ProjectedDataAccess is not null &&
item.ItemToMonitor?.AttributeId == Attributes.Value) continue;
if (target is { } projected && IsProjectedDescendant(projected) && identity is not null && ProjectedDataAccess is { } access &&
item.ItemToMonitor?.AttributeId == Attributes.Value)
{
// #940: a refused projected item is answered PER ITEM here (outside Lock), classified like Read: a lapse the
// caller is granted is retryable (its renewal was awaited by CreateMonitoredItemsAsync, or starts now), only a
// real refusal is BadUserAccessDenied. Thrown from the item manager instead, it faulted the whole request.
if (ProjectedSubscribeRefusal(access, projected, identity) is { } refusal)
{
item.Processed = true;
errors[ii] = refusal;
if (refusal.Code == StatusCodes.BadUserAccessDenied.Code) denied++;
}
continue;
}
if (Permits(identity, OpcUaOperation.CreateMonitoredItems, target!.Value)) continue;
item.Processed = true;
@@ -8988,8 +8983,8 @@ 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 renewalTasks = new Task<ProjectedRenewalResult>?[nodesToProcess.Count];
List<Task<ProjectedRenewalResult>>? renewals = null;
var access = ProjectedDataAccess;
for (var i = 0; i < nodesToProcess.Count; i++)
{
@@ -8998,7 +8993,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
// #922: a projected node refused only because its metadata lease lapsed is renewed within this request — never
// answered access-denied for the lapse. A caller without the grant is classified Denied and never reaches the origin.
if (vetoes[i] is null || identity is null || access is null || !IsProjectedDescendant(handle.NodeId)) continue;
Task<bool>? renewal = null;
Task<ProjectedRenewalResult>? 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;
@@ -9041,7 +9036,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
// #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 })
// #939: so is a renewal the ORIGIN refused (its operation is no longer granted) — BadUserAccessDenied, not retryable.
if (lapses[i] is ProjectedLapseOutcome.Renewing && renewalTasks[i] is
{ IsCompletedSuccessfully: true, Result: ProjectedRenewalResult.Renewed or ProjectedRenewalResult.Refused })
lapses[i] = ProjectedLapseOutcome.Denied;
if (lapses[i] is ProjectedLapseOutcome.Renewing or ProjectedLapseOutcome.Unavailable)
{
@@ -411,11 +411,22 @@ public sealed class OtOpcUaSdkServer : StandardServer
{
if (caller is null || access is null || !access.TryAcquire(item.NodeId, caller, DataOperations.Write, out demand) ||
demand is null || !demand.IsValid)
{ result[i] = StatusCodes.BadUserAccessDenied; continue; }
{
demand?.Dispose(); demand = null;
// #940: a lapsed metadata lease is not an access denial — the same classification + on-demand renewal as
// Read (#922). A caller granted the write waits (bounded) for the renewal and is then dispatched; a real
// ACL denial, a revoked node and an origin refusal (#939) stay BadUserAccessDenied.
var (acquired, refusal) = caller is null || access is null
? (null, StatusCodes.BadUserAccessDenied)
: await AcquireLapsedProjectedWriteAsync(access, item.NodeId, caller, requestHeader, requestLifetime.CancellationToken)
.ConfigureAwait(false);
if (acquired is null) { result[i] = refusal; continue; }
demand = acquired;
}
if (!manager.CanDispatchProjectedWrite()) { result[i] = StatusCodes.BadInvalidState; continue; }
var milliseconds = requestHeader is { TimeoutHint: > 0 } ? Math.Min(requestHeader.TimeoutHint, 30000u) : 30000u;
var budget = new DataBudget(TimeSpan.FromMilliseconds(milliseconds), 1, 4 * 1024 * 1024);
var outcome = await access.WriteAsync(demand, SdkValueBoundary.ToClr(item.Value.WrappedValue), budget, started,
var outcome = await access!.WriteAsync(demand, SdkValueBoundary.ToClr(item.Value.WrappedValue), budget, started,
requestLifetime.CancellationToken).ConfigureAwait(false);
result[i] = outcome.State switch
{
@@ -438,7 +449,44 @@ public sealed class OtOpcUaSdkServer : StandardServer
finally { OnRequestComplete(context); }
}
private static readonly byte[] ProjectedCursorPrefix = [0x4f, 0x54, 0x50, 0x43, 0x55, 0x41, 0x50, 0x31];
/// <summary>#940: the longest a projected Write waits for the on-demand renewal of a lapsed lease (also capped by its timeout hint).</summary>
internal static readonly TimeSpan ProjectedWriteRenewalWait = TimeSpan.FromSeconds(4);
/// <summary>
/// #940: classifies a refused projected write acquire. Denied ⇒ <c>BadUserAccessDenied</c>; a lapse the caller is granted
/// renews (bounded by <see cref="ProjectedWriteRenewalWait"/> and the request's timeout hint, no lock held) and is then
/// re-acquired; a renewal that cannot complete or start ⇒ <c>BadResourceUnavailable</c> (retryable, nothing dispatched);
/// an origin refusal or a renewed node that is still refused ⇒ <c>BadUserAccessDenied</c>.
/// </summary>
private static async Task<(IProjectedDemandLease? Demand, StatusCode Refusal)> AcquireLapsedProjectedWriteAsync(IProjectedDataAccess access,
NodeId nodeId, RoleCarryingUserIdentity caller, RequestHeader? requestHeader, CancellationToken cancellationToken)
{
ProjectedLapseOutcome lapse;
Task<ProjectedRenewalResult>? renewal = null;
try { lapse = access.RenewLapsed(nodeId, caller, DataOperations.Write, out renewal); }
catch (Exception) { lapse = ProjectedLapseOutcome.Denied; }
if (lapse == ProjectedLapseOutcome.Denied) return (null, StatusCodes.BadUserAccessDenied);
if (lapse != ProjectedLapseOutcome.Renewing || renewal is null) return (null, StatusCodes.BadResourceUnavailable);
var wait = ProjectedWriteRenewalWait;
if (requestHeader is { TimeoutHint: > 0 } && TimeSpan.FromMilliseconds(requestHeader.TimeoutHint) / 2 < wait)
wait = TimeSpan.FromMilliseconds(requestHeader.TimeoutHint) / 2; // leave the write itself the other half
try { await renewal.WaitAsync(wait, cancellationToken).ConfigureAwait(false); }
catch (Exception ex) when (ex is TimeoutException or OperationCanceledException) { return (null, StatusCodes.BadResourceUnavailable); }
if (!renewal.IsCompletedSuccessfully) return (null, StatusCodes.BadResourceUnavailable);
if (renewal.Result == ProjectedRenewalResult.Failed) return (null, StatusCodes.BadResourceUnavailable);
if (renewal.Result == ProjectedRenewalResult.Refused) return (null, StatusCodes.BadUserAccessDenied);
IProjectedDemandLease? demand = null;
try
{
if (access.TryAcquire(nodeId, caller, DataOperations.Write, out demand) && demand is { IsValid: true }) return (demand, StatusCodes.Good);
}
catch (Exception ex) when (ex is not OutOfMemoryException) { }
demand?.Dispose();
// Renewed and still refused: the two authorities disagree only on a real refusal (#922 review rule).
return (null, StatusCodes.BadUserAccessDenied);
}
private static readonly byte[] ProjectedCursorPrefix =[0x4f, 0x54, 0x50, 0x43, 0x55, 0x41, 0x50, 0x31];
private readonly object _projectedBrowseLock = new();
private readonly Dictionary<Guid, ProjectedBrowseCursor> _projectedBrowseCursors = new();
private int _maxProjectedBrowseCursors = 256;
@@ -348,6 +348,8 @@ internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, ISer
ProjectedValueWrite? initialSample = null;
ProjectedVariableDefinition? definition = null;
if (projected && !owner.TryAcquireProjectedItem(context, handle.NodeId, publishingInterval, out demand, out initialSample, out definition))
// #940: refusals known before the create are answered per item by OtOpcUaNodeManager.CreateMonitoredItems (lapse ⇒
// retryable); this is the race-only remainder (the authority changed in between).
throw new ServiceResultException(StatusCodes.BadUserAccessDenied);
uint? reservedId = null;
@@ -472,6 +474,27 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
private LossControl? _queuedLoss;
internal Action? AfterLossDequeueForTests;
private long _candidateBytes;
// #948: the acquisition whose candidate an SDK notification last consumed, while that is still the value the SDK item last
// queued (no other candidate, loss or queue reset since). Kept without the sample (no value retained): a false match only
// costs an unproven notification + a baseline request, never a borrowed proof.
private ConsumedAcquisition? _lastConsumed;
private sealed record ConsumedAcquisition(SourceBinding Binding, object SourceIdentity, TimeProvider Clock, long SourceVersion,
DataRealm Realm, string LocalIdentifier, long ProjectionGeneration, ServingIdentity Serving, uint StatusCode,
DateTime? SourceTimestampUtc, DateTime? ServerTimestampUtc)
{
internal static ConsumedAcquisition? Of(SourceBinding binding, ProjectedValueWrite sample) =>
sample.SourceVersion is > 0 and var version
? new(binding, sample.Proof.SourceIdentity, sample.Proof.Clock, version, sample.Realm, sample.LocalIdentifier,
sample.ProjectionGeneration, sample.Serving, sample.Snapshot.StatusCode, sample.Snapshot.SourceTimestampUtc,
sample.Snapshot.ServerTimestampUtc)
: null;
internal bool Matches(SourceBinding? binding, ProjectedValueWrite sample) =>
ReferenceEquals(Binding, binding) && sample.SourceVersion == SourceVersion &&
ReferenceEquals(sample.Proof.SourceIdentity, SourceIdentity) && ReferenceEquals(sample.Proof.Clock, Clock) &&
sample.Realm == Realm && sample.LocalIdentifier == LocalIdentifier && sample.ProjectionGeneration == ProjectionGeneration &&
sample.Serving == Serving && sample.Snapshot.StatusCode == StatusCode &&
sample.Snapshot.SourceTimestampUtc == SourceTimestampUtc && sample.Snapshot.ServerTimestampUtc == ServerTimestampUtc;
}
private bool _needsSnapshot;
private int _snapshotRequested;
private SourceBinding? _binding;
@@ -527,6 +550,17 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
if (!FreshForDemand(sample)) return true;
_needsSnapshot = true;
}
else if (_candidates.Count == 0 && _queuedLoss is null && _lastConsumed is { } consumed && consumed.Matches(original, sample))
{
// #948: this item already DELIVERED this acquisition and nothing has been queued since, so the SDK item's last
// value is this one: re-applying it raises no notification, and a candidate for it would never be consumed
// (it would hold its shared budget charge until the binding changed). Renew health evidence only.
if (!FreshForDemand(sample)) return true;
var successor = new SampleEvidence(original!, sample.Proof, sample.OriginAgeBounds, sample.ReceivedTimestamp);
_latestEvidence?.Clear();
_latestEvidence = successor; _reportedLoss = null;
return false;
}
}
if (!sameSource || (_needsSnapshot && sample.IsCompleteSnapshot))
{
@@ -606,7 +640,7 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
{
if (MonitoringMode == MonitoringMode.Disabled || _queuedLoss is not null || ReferenceEquals(_reportedLoss, loss.Evidence) || _retired != 0 || !ReferenceEquals(_latestEvidence, loss.Evidence) ||
!ReferenceEquals(_binding, loss.Evidence.Binding)) return;
_queuedLoss = loss;
_queuedLoss = loss; _lastConsumed = null;
try { QueueValue(new DataValue(Variant.Null, StatusCodes.BadNoCommunication, DateTimeUtc.MinValue, DateTimeUtc.MinValue),
new ServiceResult(StatusCodes.BadNoCommunication), ignoreFilters: true); }
catch (Exception) { _queuedLoss = null; }
@@ -670,7 +704,7 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
private void ClearCandidates()
{
foreach (var candidate in _candidates) candidate.Charge.Dispose();
_candidates.Clear(); _candidateBytes = 0;
_candidates.Clear(); _candidateBytes = 0; _lastConsumed = null;
}
internal void RequestBaseline()
{
@@ -704,7 +738,8 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
_definition is { } definition && _owner.IsProjectedDefinitionCurrent(_nodeId, definition);
internal void ResetHealthMonitoringMode()
{
lock (_bindingSync) { _queuedLoss = null; _reportedLoss = null; }
// A client mode change can reset the SDK item's last value: a later re-delivery may notify again, so it needs a candidate.
lock (_bindingSync) { _queuedLoss = null; _reportedLoss = null; _lastConsumed = null; }
}
internal void Retire()
{
@@ -785,10 +820,11 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
{
ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.CandidateUnique);
var matched = matching[0]; _candidates.Remove(matched); _candidateBytes -= matched.Bytes;
_lastConsumed = ConsumedAcquisition.Of(matched.Binding, matched.Sample);
evidence = matched.Binding.Capture(matched.Sample.Proof, matched.Sample.OriginAgeBounds, matched.Sample.ReceivedTimestamp);
matched.Charge.Dispose();
}
else { ProjectedDeliveryDiagnostics.Count(matching.Length == 0 ? ProjectedDeliveryDiagnostics.Event.CandidateMissing : ProjectedDeliveryDiagnostics.Event.CandidateAmbiguous); _needsSnapshot = true; }
else { ProjectedDeliveryDiagnostics.Count(matching.Length == 0 ? ProjectedDeliveryDiagnostics.Event.CandidateMissing : ProjectedDeliveryDiagnostics.Event.CandidateAmbiguous); _needsSnapshot = true; _lastConsumed = null; }
}
if (evidence is null) RequestBaseline();
var originalSample = evidence;
@@ -208,11 +208,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
// 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 readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), Task<ProjectedRenewalResult>> _lapseRenewals = new();
// #939: a failed renewal backs off briefly (Refused = false ⇒ retryable); a definitive ORIGIN refusal is held longer and
// answered Denied (BadUserAccessDenied) without another origin call until it expires.
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), (long Until, bool Refused)> _lapseRenewalBackoff = new();
private const int MaxLapseRenewalBackoffEntries = 4096;
internal const int MaxQueuedLapseRenewals = 64;
internal static readonly TimeSpan LapseRenewalBackoff = TimeSpan.FromMilliseconds(250);
/// <summary>#939: how long a definitive origin refusal of a lapsed node's renewal is answered <c>BadUserAccessDenied</c> unsent.</summary>
internal static readonly TimeSpan LapseRefusalHold = 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>
@@ -221,11 +225,12 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
private int _lapseRenewalsStarted;
/// <inheritdoc />
public ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task<bool>? renewal)
public ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation,
out Task<ProjectedRenewalResult>? renewal)
{
renewal = null;
if (caller is null || operation is not (DataOperations.Read or DataOperations.HistoryRead) || _renewalSink is not { } sink ||
_catalog is not RemoteNamespaceResolver resolver) return ProjectedLapseOutcome.Denied;
if (caller is null || operation is not (DataOperations.Read or DataOperations.HistoryRead or DataOperations.Write or DataOperations.Subscribe) ||
_renewalSink is not { } sink || _catalog is not RemoteNamespaceResolver resolver) return ProjectedLapseOutcome.Denied;
try
{
// The SDK node must still be live, and either it or its catalog proof must have lapsed — a refusal of a node whose
@@ -235,9 +240,13 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
definition.AuthorityIsCurrent() && _catalog.IsUsableProof(proof) ||
proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) ||
proof.Metadata.View.MappingId is not { } mapping || _connectionForMapping(mapping) is not { Length: > 0 } ||
(operation == DataOperations.Read && proof.MaximumSampleAge <= TimeSpan.Zero) ||
(operation is DataOperations.Read or DataOperations.Subscribe && proof.MaximumSampleAge <= TimeSpan.Zero) ||
(operation == DataOperations.HistoryRead && (!definition.Historizing || !ProjectedHistoryAccess.Advertises(proof))))
return ProjectedLapseOutcome.Denied;
// #940: a write is also gated on this node's local write role — a node that may not write refuses whatever the lease
// says, exactly as TryAcquire does.
if (operation == DataOperations.Write && _localWriteRole() is not { Allowed: true, Generation: > 0 })
return ProjectedLapseOutcome.Denied;
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
// The same grant the served operation needs, judged on everything but the lapsed lease: a caller without it is
// refused exactly as before, and never causes an origin call.
@@ -245,24 +254,25 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
return ProjectedLapseOutcome.Denied;
var key = (definition.Realm, definition.LocalIdentifier, operation);
var budget = new DataBudget(LapseRenewalTimeout, 1, Math.Min(LapseRenewalBytes, _limits.MaxUnaryBytes));
TaskCompletionSource<bool> started;
TaskCompletionSource<ProjectedRenewalResult> started;
lock (_sync)
{
if (_disposed) return ProjectedLapseOutcome.Unavailable;
if (_lapseRenewals.TryGetValue(key, out var running)) { renewal = running; return ProjectedLapseOutcome.Renewing; }
var now = Clock.GetTimestamp();
if (_lapseRenewalBackoff.TryGetValue(key, out var until))
if (_lapseRenewalBackoff.TryGetValue(key, out var held))
{
if (now < until) return ProjectedLapseOutcome.Unavailable;
// #939: a recent definitive origin refusal is an access denial, answered without another origin call.
if (now < held.Until) return held.Refused ? ProjectedLapseOutcome.Denied : ProjectedLapseOutcome.Unavailable;
_lapseRenewalBackoff.Remove(key);
}
if (_lapseRenewals.Count >= MaxQueuedLapseRenewals) return ProjectedLapseOutcome.Unavailable;
started = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
started = new TaskCompletionSource<ProjectedRenewalResult>(TaskCreationOptions.RunContinuationsAsynchronously);
_lapseRenewals.Add(key, started.Task);
}
Interlocked.Increment(ref _lapseRenewalsStarted);
// Never on the caller's thread: the renewal awaits the origin and commits through the SDK sink (node-manager Lock).
_ = Task.Run(() => RunLapseRenewalAsync(resolver, sink, key, proof, definition, nodeId, caller, identity, operation, budget, started));
_ = Task.Run(() => RunLapseRenewalAsync(resolver, sink, key, proof, definition, nodeId, identity, operation, budget, started));
renewal = started.Task;
return ProjectedLapseOutcome.Renewing;
}
@@ -271,52 +281,42 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
private async Task RunLapseRenewalAsync(RemoteNamespaceResolver resolver, IProjectedNamespacePageSink sink,
(DataRealm Realm, string LocalIdentifier, DataOperations Operation) key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, NodeId nodeId,
RoleCarryingUserIdentity caller, DataCallerIdentity identity, DataOperations operation, DataBudget budget, TaskCompletionSource<bool> completion)
DataCallerIdentity identity, DataOperations operation, DataBudget budget, TaskCompletionSource<ProjectedRenewalResult> completion)
{
var renewed = false;
var result = ProjectedRenewalResult.Failed;
try
{
renewed = await resolver.RenewExactAsync(proof, definition, nodeId, identity, null, sink, budget,
result = await resolver.RenewExactOutcomeAsync(proof, definition, nodeId, identity, null, sink, budget,
() => { lock (_sync) return !_disposed; }, CancellationToken.None, overlap: false,
authorizeAs: Operation(operation), required: operation, onDemand: true).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException) { renewed = false; }
catch (Exception ex) when (ex is not OutOfMemoryException) { result = ProjectedRenewalResult.Failed; }
finally
{
lock (_sync)
{
_lapseRenewals.Remove(key);
if (!renewed && !_disposed)
if (result != ProjectedRenewalResult.Renewed && !_disposed)
{
if (_lapseRenewalBackoff.Count >= MaxLapseRenewalBackoffEntries) EvictLapseBackoffLocked();
var delay = (long)(LapseRenewalBackoff.TotalSeconds * Clock.TimestampFrequency);
_lapseRenewalBackoff[key] = Clock.GetTimestamp() + Math.Max(1, delay);
var refused = result == ProjectedRenewalResult.Refused;
var delay = (long)((refused ? LapseRefusalHold : LapseRenewalBackoff).TotalSeconds * Clock.TimestampFrequency);
_lapseRenewalBackoff[key] = (Clock.GetTimestamp() + Math.Max(1, delay), refused);
}
}
}
// A Read answered retryable while the lease renewed: fetch the value now, through the ordinary authorized path, so the
// client's retry is served from the fresh sample instead of starting another cold read.
if (renewed && operation == DataOperations.Read)
{
IProjectedDemandLease? demand = null;
try
{
if (TryAcquire(nodeId, caller, DataOperations.Read, out demand) && demand is not null &&
ScheduleRead(demand, new DataBudget(LapseRenewalTimeout, 1, ProjectedReadBytes), Clock.GetTimestamp())) demand = null;
}
catch (Exception ex) when (ex is not OutOfMemoryException) { }
finally { demand?.Dispose(); }
}
completion.TrySetResult(renewed);
// #938: the Read that started this renewal reads the origin itself, within its own request, once it commits — so the
// renewal no longer schedules a separate cache-warming read.
completion.TrySetResult(result);
}
// 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();
var expired = _lapseRenewalBackoff.Where(entry => entry.Value.Until <= 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);
if (expired.Length == 0) _lapseRenewalBackoff.Remove(_lapseRenewalBackoff.MinBy(entry => entry.Value.Until).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;
@@ -860,21 +860,46 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
}
public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp)
{
if (demand is not Demand item || item.RequestedOperation != DataOperations.Read || !item.IsValid || budget is null) return false;
if (!TryAdmitRead(demand, budget, requestStartedTimestamp, out var item, out var boundedBudget)) return false;
_ = Task.Run(() => ReadCoreAsync(item!, boundedBudget!, requestStartedTimestamp, CancellationToken.None, ownsDemand: true)); return true;
}
/// <inheritdoc />
public Task<ProjectedOriginRead> ReadNowAsync(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp,
CancellationToken cancellationToken)
{
// #938: the same admission (unary count + bytes) and the same authenticated, freshness-checked, cache-publishing read as
// ScheduleRead — but the caller awaits it and is served what it read. The caller keeps the demand. Admission is decided
// here, synchronously, so NotAdmitted is an already-completed task.
if (cancellationToken.IsCancellationRequested) return Task.FromResult(ProjectedOriginRead.NoValue);
if (!TryAdmitRead(demand, budget, requestStartedTimestamp, out var item, out var boundedBudget))
return Task.FromResult(demand is Demand { IsValid: true } ? ProjectedOriginRead.NotAdmitted : ProjectedOriginRead.NoValue);
return Task.Run(async () =>
{
var value = await ReadCoreAsync(item!, boundedBudget!, requestStartedTimestamp, cancellationToken, ownsDemand: false).ConfigureAwait(false);
return value is null ? ProjectedOriginRead.NoValue : new ProjectedOriginRead(ProjectedOriginReadStatus.Served, value);
}, CancellationToken.None);
}
private bool TryAdmitRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp, out Demand? item, out DataBudget? boundedBudget)
{
item = null; boundedBudget = null;
if (demand is not Demand candidate || candidate.RequestedOperation != DataOperations.Read || !candidate.IsValid || budget is null) return false;
try { budget.Validate(); } catch (ArgumentException) { return false; }
var elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp());
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return false;
// The request's byte budget is an upper bound. Narrow it to this adapter's
// configured physical limit before admission and before remote dispatch.
var boundedBudget = budget with { MaxBytes = Math.Min(budget.MaxBytes, _limits.MaxUnaryBytes) };
var bounded = budget with { MaxBytes = Math.Min(budget.MaxBytes, _limits.MaxUnaryBytes) };
lock (_sync)
{
if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || boundedBudget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) return false;
_unaryCount++; _unaryBytes += boundedBudget.MaxBytes;
if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || bounded.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !candidate.TryHold()) return false;
_unaryCount++; _unaryBytes += bounded.MaxBytes;
}
_ = Task.Run(() => ReadCoreAsync(item, boundedBudget, requestStartedTimestamp)); return true;
item = candidate; boundedBudget = bounded;
return true;
}
private async Task ReadCoreAsync(Demand demand, DataBudget budget, long started)
// Returns the read sample when it is servable to the demand's caller: authenticated by the demand's current binding, fresh
// within the mapping's stale timeout, and published to (or already superseded in) the projection cache. Null otherwise.
private async Task<DataValueSnapshot?> ReadCoreAsync(Demand demand, DataBudget budget, long started, CancellationToken callerStop, bool ownsDemand)
{
IGrpcDataAdapterConnectionLease? connection = null;
try
@@ -882,14 +907,14 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
var original = demand.CurrentBinding;
var originalProof = original.Proof;
var remaining = budget.Timeout - Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (remaining <= TimeSpan.Zero || !demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return;
if (remaining <= TimeSpan.Zero || !demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return null;
var connectionId = _connectionForMapping(originalProof.Metadata.View.MappingId!);
if (string.IsNullOrWhiteSpace(connectionId)) return;
if (string.IsNullOrWhiteSpace(connectionId)) return null;
using var timeout = new CancellationTokenSource(remaining, Clock);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, demand.CancellationToken);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, demand.CancellationToken, callerStop);
connection = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false);
if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) || connection.CancellationToken.IsCancellationRequested ||
!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return;
!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return null;
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
var readStarted = Clock.GetTimestamp();
var result = await connection.Connection.ReadAsync(new DataReadRequest([new ReadItem("0", originalProof.OriginMetadata.View, null)], budget with { Timeout = remaining }), route.Token).ConfigureAwait(false);
@@ -897,32 +922,36 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
{
if (result.Count != 1 || result[0].CorrelationId != "0" || result[0].Status != DataItemStatus.Good || result[0].Readiness != DataReadiness.Ready ||
result[0].Sample is not { } sample || sample.Serving != originalProof.Lease.Serving || sample.Version <= 0 || !demand.IsValid ||
!ReferenceEquals(demand.CurrentBinding, original) || route.IsCancellationRequested) return;
!ReferenceEquals(demand.CurrentBinding, original) || route.IsCancellationRequested) return null;
result[0].AgeBounds.Validate();
// An unstamped implementation is conservatively anchored before the read call.
var received = result[0].FreshnessObservedTimestamp ?? readStarted;
if (!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return;
if (sample.Value.EstimatedRetainedBytes > budget.MaxBytes) return;
if (!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return null;
if (sample.Value.EstimatedRetainedBytes > budget.MaxBytes) return null;
var payload = DecodeValue(sample.Value, originalProof.OriginMetadata);
var snapshot = new DataValueSnapshot(payload, sample.StatusCode, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime);
var source = GetSource(demand, connectionId);
if (source is null) return;
if (source is null) return null;
lock (source.Gate)
{
if (!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original) || !source.IsValid || sample.Version <= source.LastVersion || route.IsCancellationRequested ||
!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return;
if (!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original) || !source.IsValid || route.IsCancellationRequested ||
!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return null;
// The cache already holds this acquisition or a newer one: nothing to publish, but what was read is still an
// authenticated, fresh origin sample of this request (#938 serves it).
if (sample.Version <= source.LastVersion) return snapshot;
var update = new ProjectedValueUpdate(source.Route, snapshot, result[0].AgeBounds, received, source.CaptureReadProof(originalProof), true, originalProof.MaximumSampleAge, sample.Version);
if (_publisher.TryPublish([update])) { source.LastVersion = sample.Version; source.CacheLocked(update, sample.Version); }
else if (!ProjectedEvidenceRetirement.CanDrop(update.SourceProof)) source.Invalidate();
if (_publisher.TryPublish([update])) { source.LastVersion = sample.Version; source.CacheLocked(update, sample.Version); return snapshot; }
if (!ProjectedEvidenceRetirement.CanDrop(update.SourceProof)) source.Invalidate();
return null;
}
}
finally { foreach (var item in result) item.Dispose(); }
}
catch (Exception) { }
catch (Exception) { return null; }
finally
{
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
finally { demand.Dispose(); demand.ReleaseHold(); lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } }
finally { if (ownsDemand) demand.Dispose(); demand.ReleaseHold(); lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } }
}
}
public async Task<DataWriteOutcome> WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget,
@@ -312,21 +312,39 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
// Refresh exactly one already-owned projected item. This deliberately creates no Browse
// page, cursor or sibling visibility and does not create a physical subscription.
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,
bool onDemand = false) =>
await RenewExactOutcomeAsync(previous, definition, nodeId, caller, configured, sink, budget, demandActive, cancellationToken,
overlap, authorizeAs, required, onDemand).ConfigureAwait(false) == ProjectedRenewalResult.Renewed;
/// <summary>
/// <see cref="RenewExactAsync"/> with the reason a renewal did not commit (#939): <see cref="ProjectedRenewalResult.Refused"/>
/// ONLY for a definitive refusal BY THE ORIGIN — the call answered <c>PERMISSION_DENIED</c>, the item was answered
/// <c>Denied</c>, the principal no longer holds Metadata, or the metadata no longer grants <paramref name="required"/>.
/// Everything else (unreachable / unready / non-primary origin, capacity, timeout, a changed shape, a local fence) is
/// <see cref="ProjectedRenewalResult.Failed"/>, i.e. retryable.
/// </summary>
internal async Task<ProjectedRenewalResult> RenewExactOutcomeAsync(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,
bool onDemand = false)
{
const ProjectedRenewalResult Failed = ProjectedRenewalResult.Failed;
const ProjectedRenewalResult Refused = ProjectedRenewalResult.Refused;
// #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.
if (authorizeAs is not (OpcUaOperation.CreateMonitoredItems or OpcUaOperation.Read or OpcUaOperation.HistoryRead) ||
required is not (DataOperations.Subscribe or DataOperations.Read or DataOperations.HistoryRead)) return false;
// renews for the operation the caller is performing (Read / HistoryRead / #940 Write / Subscribe) and requires exactly
// that bit at the origin.
if (authorizeAs is not (OpcUaOperation.CreateMonitoredItems or OpcUaOperation.Read or OpcUaOperation.HistoryRead or OpcUaOperation.WriteOperate) ||
required is not (DataOperations.Subscribe or DataOperations.Read or DataOperations.HistoryRead or DataOperations.Write)) return Failed;
var mapping = previous.Metadata.View.MappingId;
if (mapping is null || previous.Subject.Scope.Segments.Count == 0) return false;
if (mapping is null || previous.Subject.Scope.Segments.Count == 0) return Failed;
ProjectedMappingBinding binding;
lock (_sync)
{
if (_disposed || !_mappings.TryGetValue(mapping, out binding!)) return false;
if (_disposed || !_mappings.TryGetValue(mapping, out binding!)) return Failed;
}
bool CallerAllowed() => demandActive() && (configured is not null
? configured.Matches(mapping, previous.Metadata.View, binding.LocalAuthority)
@@ -339,16 +357,16 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
!string.Equals(previous.Subject.Scope.ClusterId, binding.LocalScope.ClusterId, StringComparison.OrdinalIgnoreCase) ||
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;
!previous.Subject.LocalAncestry.SequenceEqual(binding.LocalAncestry, StringComparer.OrdinalIgnoreCase)) return Failed;
// 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 (!await slots.WaitAsync(onDemand ? budget.Timeout : TimeSpan.Zero, cancellationToken).ConfigureAwait(false)) return Failed;
if (onDemand)
{
var left = budget.Timeout - System.Diagnostics.Stopwatch.GetElapsedTime(queued);
if (left <= TimeSpan.Zero) { slots.Release(); return false; }
if (left <= TimeSpan.Zero) { slots.Release(); return Failed; }
budget = budget with { Timeout = left };
}
IGrpcDataAdapterConnectionLease? connection = null;
@@ -359,22 +377,31 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token);
connection = await _source.AcquireAsync(binding.Mapping.DataConnectionId, linked.Token).ConfigureAwait(false);
if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) ||
!string.Equals(connection.Connection.Target.ExpectedClusterId, previous.OriginMetadata.View.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase)) return false;
!string.Equals(connection.Connection.Target.ExpectedClusterId, previous.OriginMetadata.View.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase)) return Failed;
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
var capabilities = await connection.Connection.GetCapabilitiesAsync(budget, route.Token).ConfigureAwait(false);
capabilities.Validate();
var serving = capabilities.Serving;
var target = connection.Connection.Target;
if (!capabilities.MetadataItemLeases || capabilities.Readiness != DataReadiness.Ready ||
(capabilities.Operations & DataOperations.Metadata) == 0 || serving.ServingGeneration <= 0 ||
if (!capabilities.MetadataItemLeases || capabilities.Readiness != DataReadiness.Ready || serving.ServingGeneration <= 0 ||
!(string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) ||
target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.ReadyReplica && string.Equals(serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase))) return false;
target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.ReadyReplica && string.Equals(serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase))) return Failed;
// #939: a ready, authenticated origin that no longer grants this principal Metadata at all has refused the renewal.
if ((capabilities.Operations & DataOperations.Metadata) == 0) return Refused;
var elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return false;
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return Failed;
var results = await connection.Connection.GetMetadataAsync(new([previous.OriginMetadata.View],
budget with { MaxItems = 1, Timeout = budget.Timeout - elapsed }), route.Token).ConfigureAwait(false);
elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || linked.IsCancellationRequested) return false;
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || linked.IsCancellationRequested) return Failed;
// #939: the origin's own verdict on this item — Denied, or a Good answer that no longer grants the operation — is a
// definitive refusal (the consumer answers BadUserAccessDenied), not a lapse to retry.
if (results.Count == 1 && results[0].CorrelationId == "0" &&
(results[0].Status == DataItemStatus.Denied ||
results[0].Status == DataItemStatus.Good && results[0].Value is { } granted && granted.View == previous.OriginMetadata.View &&
(binding.Mapping.AllowedOperations & required) == required &&
((granted.AllowedOperations & required) == 0 || required == DataOperations.Write && !granted.Writable)))
return Refused;
if (results.Count != 1 || results[0].CorrelationId != "0" || results[0].Status != DataItemStatus.Good ||
results[0].Value is not { } metadata || results[0].Lease is not { } remoteLease ||
metadata.View != previous.OriginMetadata.View || metadata.Serving != serving || metadata.CatalogRevision != serving.CatalogEpoch ||
@@ -385,14 +412,14 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
metadata.ArrayElementKind != previous.OriginMetadata.ArrayElementKind ||
!metadata.Dimensions.SequenceEqual(previous.OriginMetadata.Dimensions) ||
(metadata.AllowedOperations & binding.Mapping.AllowedOperations & required) == 0 ||
!IsCurrent(binding) || !CallerAllowed() || connection.CancellationToken.IsCancellationRequested) return false;
!IsCurrent(binding) || !CallerAllowed() || connection.CancellationToken.IsCancellationRequested) return Failed;
metadata.Validate(); remoteLease.Validate();
var generation = _cache.CaptureGeneration(mapping);
var maximumLease = TimeSpan.FromMilliseconds(binding.Mapping.MetadataLeaseMilliseconds);
if (caller?.CredentialExpiresUtc is { } expiry)
{
var remaining = expiry - Clock.GetUtcNow();
if (remaining <= TimeSpan.Zero) return false;
if (remaining <= TimeSpan.Zero) return Failed;
if (remaining < maximumLease) maximumLease = remaining;
}
var lease = new BoundProjectionLease(new MetadataAuthorityLease(serving, remoteLease, started, maximumLease, TimeSpan.Zero, Clock),
@@ -406,10 +433,10 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds));
var guard = new ExactAuthority(renewed);
if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, authorizeAs,
mapped.View, serving, subject, resolver, lease)) return false;
mapped.View, serving, subject, resolver, lease)) return Failed;
var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent,
mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime, Historizing = ProjectedHistoryAccess.Advertises(renewed) };
return sink.TryRenewExact(nodeId, definition, newDefinition, () =>
var committedRenewal = sink.TryRenewExact(nodeId, definition, newDefinition, () =>
{
var duration = Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (linked.IsCancellationRequested || cancellationToken.IsCancellationRequested || connection.CancellationToken.IsCancellationRequested ||
@@ -422,8 +449,11 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
guard.Adopt(actual);
return guard.IsCurrent();
});
return committedRenewal ? ProjectedRenewalResult.Renewed : Failed;
}
catch (Exception ex) when (ex is not OutOfMemoryException) { return false; }
// #939: the origin answered the call itself PERMISSION_DENIED (e.g. the operation is no longer granted to this
// principal). The connection reports it as the cause of its "no ready endpoint" failure.
catch (Exception ex) when (ex is not OutOfMemoryException) { return IsOriginPermissionDenied(ex) ? Refused : Failed; }
finally
{
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
@@ -431,6 +461,12 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
finally { slots.Release(); }
}
}
internal static bool IsOriginPermissionDenied(Exception? ex)
{
for (var depth = 0; ex is not null && depth < 8; ex = ex.InnerException, depth++)
if (ex is Grpc.Core.RpcException { StatusCode: Grpc.Core.StatusCode.PermissionDenied }) return true;
return false;
}
public void Dispose()
{
ProjectedMappingBinding[] old;