Merge master into #937 (scenarios: keep A09 + F937)
This commit is contained in:
@@ -11,6 +11,11 @@ public sealed class DeferredProjectedNodeAccess(DeferredAddressSpaceSink deferre
|
||||
definition = null;
|
||||
return deferred.GetCapability<IProjectedNodeLookup>()?.TryResolve(nodeId, out definition) == true;
|
||||
}
|
||||
public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition)
|
||||
{
|
||||
definition = null;
|
||||
return deferred.GetCapability<IProjectedNodeLookup>()?.TryResolveForRenewal(nodeId, out definition) == true;
|
||||
}
|
||||
public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId)
|
||||
{
|
||||
nodeId = null;
|
||||
|
||||
@@ -18,6 +18,20 @@ public interface IProjectedDemandLease : IDisposable
|
||||
bool IsValid { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #922: how a refused <see cref="IProjectedDataAccess.TryAcquire"/> of a projected node is classified. A lapsed metadata
|
||||
/// lease is NOT an authorization failure: only <see cref="Denied"/> is answered <c>BadUserAccessDenied</c>.
|
||||
/// </summary>
|
||||
public enum ProjectedLapseOutcome
|
||||
{
|
||||
/// <summary>Not a lapse the caller may wait out (no grant, not a lapse at all, or a revoked authority).</summary>
|
||||
Denied,
|
||||
/// <summary>The caller is granted the subject; its lapsed lease is being renewed (the task completes with the outcome).</summary>
|
||||
Renewing,
|
||||
/// <summary>The caller is granted the subject, but no renewal can run right now (capacity, a recent failure): retry later.</summary>
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
/// <summary>Nonblocking local admission and bounded scheduling for projected data.</summary>
|
||||
public interface IProjectedDataAccess
|
||||
{
|
||||
@@ -30,6 +44,17 @@ public interface IProjectedDataAccess
|
||||
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.
|
||||
/// </summary>
|
||||
ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task<bool>? renewal)
|
||||
{
|
||||
renewal = null;
|
||||
return ProjectedLapseOutcome.Denied;
|
||||
}
|
||||
/// <summary>True while a demand or physically retained operation still owns this projection.</summary>
|
||||
bool HasLiveDemand(DataRealm realm, string localIdentifier) => true;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,12 @@ public interface IProjectedNodeLookup
|
||||
{
|
||||
bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition);
|
||||
bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId);
|
||||
/// <summary>
|
||||
/// #922: the committed, still-live definition of a projected node WHETHER OR NOT its authority is current — used only to
|
||||
/// renew a lapsed lease in place (the renewal re-proves authority at the origin and commits against this exact definition).
|
||||
/// Confers nothing; never use it to serve.
|
||||
/// </summary>
|
||||
bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition) { definition = null; return false; }
|
||||
}
|
||||
|
||||
/// <summary>Installs and retires locally authorized mapping anchors.</summary>
|
||||
|
||||
@@ -4428,6 +4428,23 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #922: like <see cref="TryResolve"/> but WITHOUT the authority check, so a node whose metadata lease lapsed can be renewed
|
||||
/// in place. Lock-free (committed snapshot), confers nothing.
|
||||
/// </summary>
|
||||
public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition)
|
||||
{
|
||||
var committed = Volatile.Read(ref _committedProjectedDefinitions);
|
||||
if (!_disposing && committed.TryGetValue(nodeId, out var current) && current.Lifetime.IsActive &&
|
||||
Volatile.Read(ref _committedProjectedDefinitions).TryGetValue(nodeId, out var latest) && ReferenceEquals(current, latest))
|
||||
{
|
||||
definition = current;
|
||||
return true;
|
||||
}
|
||||
definition = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
private int _maxProjectedNodes = 4096;
|
||||
private long _maxProjectedNodeBytes = 16 * 1024 * 1024;
|
||||
private long _projectedNodeBytes;
|
||||
@@ -6307,8 +6324,18 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
if (identity is null || access is null || !access.TryAcquire(projected.NodeId, identity, DataOperations.Read, out demand) ||
|
||||
demand is null || !demand.IsValid)
|
||||
{
|
||||
errors[ii] = StatusCodes.BadUserAccessDenied;
|
||||
values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied);
|
||||
demand?.Dispose(); demand = null;
|
||||
// #922: a lapsed metadata lease is not an authorization failure. A caller granted the node gets the same
|
||||
// retryable answer as a cold read while the lease renews on demand (off this thread, no Lock held).
|
||||
var lapse = identity is null || access is null ? ProjectedLapseOutcome.Denied
|
||||
: access.RenewLapsed(projected.NodeId, identity, DataOperations.Read, out _);
|
||||
if (lapse == ProjectedLapseOutcome.Denied)
|
||||
{
|
||||
errors[ii] = StatusCodes.BadUserAccessDenied;
|
||||
values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied);
|
||||
}
|
||||
else values[ii] = new DataValue(Variant.Null, lapse == ProjectedLapseOutcome.Renewing
|
||||
? StatusCodes.BadWaitingForInitialData : StatusCodes.BadResourceUnavailable);
|
||||
continue;
|
||||
}
|
||||
ProjectedValueWrite? cached;
|
||||
@@ -6349,6 +6376,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
if (Permits(identity, OpcUaOperation.Read, nodeToRead.NodeId)) continue;
|
||||
|
||||
nodeToRead.Processed = true;
|
||||
// #922: an attribute of a projected node whose lease lapsed — retryable while it renews, never access-denied.
|
||||
if (identity is not null && IsProjectedDescendant(nodeToRead.NodeId) && ProjectedDataAccess is { } lapsedAccess &&
|
||||
ClassifyProjectedLapse(lapsedAccess, nodeToRead.NodeId, identity, DataOperations.Read) != ProjectedLapseOutcome.Denied)
|
||||
{
|
||||
values[ii] = new DataValue(Variant.Null, StatusCodes.BadResourceUnavailable);
|
||||
continue;
|
||||
}
|
||||
errors[ii] = StatusCodes.BadUserAccessDenied;
|
||||
values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied);
|
||||
denied++;
|
||||
@@ -8935,18 +8969,75 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
var identity = (context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity
|
||||
?? context.OperationContext?.UserIdentity as RoleCarryingUserIdentity;
|
||||
|
||||
var allowed = new List<NodeHandle>(nodesToProcess.Count);
|
||||
foreach (var handle in nodesToProcess)
|
||||
{
|
||||
var veto = _authorizer?.AuthorizeIfRequired(
|
||||
ServiceResult? Veto(NodeHandle handle) => _authorizer?.AuthorizeIfRequired(
|
||||
identity, OpcUaOperation.HistoryRead, handle.NodeId, RealmOf(handle.NodeId), cached: false)
|
||||
?? (_authorizer is null && _mappedSubjectResolver is not null ? new ServiceResult(StatusCodes.BadUserAccessDenied) : null);
|
||||
?? (_authorizer is null && _mappedSubjectResolver is not null ? new ServiceResult(StatusCodes.BadUserAccessDenied) : null);
|
||||
|
||||
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++)
|
||||
{
|
||||
var handle = nodesToProcess[i];
|
||||
vetoes[i] = Veto(handle);
|
||||
// #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;
|
||||
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.
|
||||
// #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]);
|
||||
}
|
||||
|
||||
var allowed = new List<NodeHandle>(nodesToProcess.Count);
|
||||
for (var i = 0; i < nodesToProcess.Count; i++)
|
||||
{
|
||||
var handle = nodesToProcess[i];
|
||||
var veto = vetoes[i];
|
||||
if (veto is null)
|
||||
{
|
||||
allowed.Add(handle);
|
||||
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.
|
||||
errors[handle.Index] = new ServiceResult(StatusCodes.BadResourceUnavailable);
|
||||
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadResourceUnavailable };
|
||||
continue;
|
||||
}
|
||||
|
||||
// Set both slots explicitly rather than relying on the base's pre-seeded
|
||||
// BadHistoryOperationUnsupported — "unsupported" would tell the client the node has no history,
|
||||
// which is a different fact from "you may not read it" and sends them debugging the wrong thing.
|
||||
@@ -8957,6 +9048,20 @@ 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, 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,
|
||||
RoleCarryingUserIdentity identity, DataOperations operation)
|
||||
{
|
||||
try { return access.RenewLapsed(nodeId, identity, operation, out _); }
|
||||
catch (Exception) { return ProjectedLapseOutcome.Denied; }
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve (H3: projected handles go remote).</remarks>
|
||||
protected override void HistoryReadRawModified(
|
||||
|
||||
@@ -55,6 +55,9 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre
|
||||
/// <inheritdoc />
|
||||
public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) => _nodeManager.TryResolve(nodeId, out definition);
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition) => _nodeManager.TryResolveForRenewal(nodeId, out definition);
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) => _nodeManager.TryGetNodeId(namespaceUri, identifier, out nodeId);
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
/// failover and re-deploys, identical on both pair members (the secret is a per-cluster <c>${secret:}</c>), and
|
||||
/// equal across every listing and principal (m-T6), so a consumer dedupes a condition's Raw and UNS placements.
|
||||
/// Being keyed, it cannot be dictionary-reversed from guessable RawPaths, and it carries no RawPath or driver id
|
||||
/// (unlike <c>Metadata.stable_source_id</c>, #916).
|
||||
/// (the v1 <c>Metadata.stable_source_id</c> did, and is no longer sent, #916).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Without a secret the origin advertises no <c>conditions</c> capability (fail closed): <see cref="IsAvailable"/>
|
||||
|
||||
@@ -13,11 +13,18 @@ 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);
|
||||
internal bool ExpiredNaturally => remote.ExpiredNaturally && LiveContext;
|
||||
public bool IsValid => LiveContext && remote.IsValid;
|
||||
/// <summary>
|
||||
/// #922: the authority is gone ONLY because it is transient — the remote lease's time ran out or its route was
|
||||
/// replaced — while the local catalog authority, the mapping binding and the cache generation are all still current
|
||||
/// and nothing revoked it. Such a lapse is renewed by an exact metadata refresh, never answered as an access denial.
|
||||
/// </summary>
|
||||
internal bool Renewable => !remote.Invalidated && local.IsActive && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation);
|
||||
internal ProjectionLeaseDiagnostics CaptureDiagnostics() => new(RouteAlive, local.IsActive,
|
||||
remote.IsValid, bindingCurrent(), cache.IsCurrentGeneration(mapping, generation));
|
||||
}
|
||||
|
||||
@@ -394,11 +394,19 @@ public sealed partial class LocalDataServices : IDataConnectionFactory
|
||||
long bytes = 256;
|
||||
var maximum = Math.Min(request.Budget.MaxItems, limits.MaxPageItems);
|
||||
var scanned = 0;
|
||||
while (offset < children.Count && page.Count < maximum && scanned++ < maximum)
|
||||
while (offset < children.Count && page.Count < maximum && scanned < maximum)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (Expired(start, request.Budget)) return Task.FromResult(Empty(DataItemStatus.Unavailable));
|
||||
var child = children[offset++];
|
||||
// #917: an unsupported value node (an alarm-bearing tag, or a data type v1 cannot carry) is never listed. Every
|
||||
// consumer build applies a browse page all-or-nothing and cannot materialise one, so listing it made the whole
|
||||
// folder unbrowsable on the consumer (BadNoCommunication). It stays addressable (GetMetadata/Read/Subscribe on it
|
||||
// answer Unsupported). An export rooted at it still compiles but grants nothing. A skipped node is not counted
|
||||
// against the scan bound (it costs one check; the budget timeout above still bounds the call), so the skip never
|
||||
// yields an empty Complete=false page.
|
||||
if (child.Source is not null && !child.Supported) continue;
|
||||
scanned++;
|
||||
if ((request.Filter is { Length: > 0 } filter && !child.Metadata.BrowseName.Contains(filter, StringComparison.Ordinal))
|
||||
|| !Allowed(catalog, context, child, DataOperations.Browse)) continue;
|
||||
var metadata = Metadata(catalog, context, target, child);
|
||||
|
||||
+13
-2
@@ -92,11 +92,16 @@ public sealed partial class LocalExportCatalog
|
||||
BackingSourceKey? source = null, DataValueKind valueKind = DataValueKind.Null, bool writable = false,
|
||||
bool array = false, uint? length = null, bool supported = true, bool enabled = true)
|
||||
{
|
||||
writable &= supported; // #917 review: an unsupported value node is never writable, not even in internal metadata
|
||||
var operations = source is null ? navigation : data | (writable ? DataOperations.Write : DataOperations.None);
|
||||
var metadata = new DataMetadata(view, name, source is null ? "Folder" : supported ? "Variable" : "UnsupportedVariable",
|
||||
array && supported ? DataValueKind.Array : valueKind, array && supported ? 1 : -1,
|
||||
array && supported ? Array.AsReadOnly(new[] { length is { } n ? checked((int)n) : 0 }) : [],
|
||||
writable, operations, serving.CatalogEpoch, source?.StableSourceId, null, false,
|
||||
// #916: Metadata.stable_source_id is never sent. The internal key of a driver source is
|
||||
// "<len>:<driverInstanceId><RawPath>" (SourceKey.ForDriver), which told a UNS-only peer the origin's driver ids
|
||||
// and RawPaths; no consumer uses the field (it is optional on the wire and old consumers decode its absence as
|
||||
// null). Acquisition keys on the LocalDataNode.Source BackingSourceKey, which is unchanged.
|
||||
writable, operations, serving.CatalogEpoch, null, null, false,
|
||||
array && supported ? valueKind : null);
|
||||
nodes.Add(new(kind, id, metadata, scope, parent, source, supported, enabled));
|
||||
views.Add((view.Realm, kind, id.ToUpperInvariant()), view);
|
||||
@@ -131,7 +136,13 @@ public sealed partial class LocalExportCatalog
|
||||
var enabled = deviceById[tagById[plan.TagId].DeviceId].Enabled && driverById[plan.DriverInstanceId].Enabled;
|
||||
rawSources.Add(plan.NodeId, (source, enabled));
|
||||
var kind = ValueKind(plan.DataType);
|
||||
var supported = kind != DataValueKind.Unspecified && (!plan.IsArray || DataValue.IsSupportedArrayElementKind(kind));
|
||||
// #917: an alarm-bearing tag never gets a value (DriverHostActor keeps it out of the value fan-out; #896 gives it
|
||||
// no UNS variable), so it is an unsupported value node: Browse does not list it (LocalDataServices) and every
|
||||
// value operation answers Unsupported, instead of a Variable a consumer would wait on forever. The node is KEPT so
|
||||
// an export rooted at it still compiles, but such a root grants nothing: its values are unsupported and its
|
||||
// condition placement sits under its folder, not under the tag. The alarm is forwarded as a condition (A1–A4).
|
||||
var supported = plan.Alarm is null && kind != DataValueKind.Unspecified
|
||||
&& (!plan.IsArray || DataValue.IsSupportedArrayElementKind(kind));
|
||||
var rawView = View(DataRealm.Raw, plan.NodeId, scope);
|
||||
Add("RawTag", plan.TagId, plan.Name, rawView, scope, RawParent(scope), source,
|
||||
supported ? kind : DataValueKind.Null, plan.Writable && (!plan.IsArray || plan.ArrayWritable),
|
||||
|
||||
@@ -47,6 +47,8 @@ public sealed class MetadataAuthorityLease : IDataAuthorizationLease
|
||||
}
|
||||
}
|
||||
internal TimeSpan UsableDuration => _usableDuration;
|
||||
/// <summary>True once <see cref="Invalidate"/> ran: a revocation, never renewable (#922).</summary>
|
||||
internal bool Invalidated => Volatile.Read(ref _invalidated) != 0;
|
||||
internal bool ExpiredNaturally => Volatile.Read(ref _invalidated) == 0 &&
|
||||
_clock.GetElapsedTime(_requestStart, _clock.GetTimestamp()) >= _usableDuration;
|
||||
public bool IsValid
|
||||
|
||||
@@ -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();
|
||||
@@ -176,15 +179,26 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
|
||||
if (!guard.IsCurrent()) return Empty(ProjectedBrowseReadiness.Unavailable);
|
||||
var retainedBytes = checked(sourceGuard.RetainedBytes + 2048L + 2L * (snapshot.Continuation?.Length ?? 0) +
|
||||
expectedIds.Sum(node => 128L + 2L * node.IdentifierAsString.Length));
|
||||
// #922: a re-browse served from a cached page must still renew a lease that is running out — otherwise a client that
|
||||
// re-browses to refresh a node it reads gets nothing until the page itself lapses. Past half its life an initial page
|
||||
// is served as is AND refreshed in the background (at most one in flight per page key; a fresh page is untouched).
|
||||
if (input.Cursor is null && lease is BoundProjectionLease bound && bound.Remaining < bound.UsableDuration / 2)
|
||||
_ = TrySchedule(new WorkKey(input.Parent, identity, input.Cursor, maximum), request, anchor, input.Parent, refresh: true);
|
||||
return new(ProjectedBrowseReadiness.Ready, Array.AsReadOnly(expectedIds), snapshot.Continuation, snapshot.Complete,
|
||||
guard.IsCurrent, retainedBytes);
|
||||
}
|
||||
if (snapshot.Status == ProjectionPageStatus.InvalidContinuation) return Empty(ProjectedBrowseReadiness.InvalidContinuation);
|
||||
var key = new WorkKey(input.Parent, identity, input.Cursor, maximum);
|
||||
return TrySchedule(new WorkKey(input.Parent, identity, input.Cursor, maximum), request, anchor, input.Parent, refresh: false);
|
||||
}
|
||||
|
||||
private ProjectedBrowsePage TrySchedule(WorkKey key, ProjectedBrowseRequest request, Installed anchor, NodeId exactParent, bool refresh)
|
||||
{
|
||||
lock (_resultGate)
|
||||
{
|
||||
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) || !_refreshing.TryAdd(exactParent, 0)))
|
||||
return Empty(ProjectedBrowseReadiness.Pending);
|
||||
if (_failures.TryGetValue(key, out var failure))
|
||||
return Empty(failure.Status switch
|
||||
{
|
||||
@@ -193,11 +207,14 @@ 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++;
|
||||
}
|
||||
var exactParent = input.Parent;
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
var result = ProjectionPageStatus.Unavailable;
|
||||
@@ -208,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)
|
||||
{
|
||||
|
||||
@@ -106,7 +106,8 @@ public sealed class ProjectedCatalogCache
|
||||
private static ParentKey Key(ProjectedBrowseRequest request) => new(request.MappingId.ToUpperInvariant(), request.Parent,
|
||||
request.Filter, request.Continuation, request.Caller, request.ConfiguredCapability);
|
||||
private static (string Mapping, DataView Parent) Parent(string mapping, DataView parent) => (mapping.ToUpperInvariant(), parent);
|
||||
private bool ValidCore(ProjectedNodeProof proof) => proof.Generation > 0 && proof.Lease.IsValid && proof.Lease.Serving.ServingGeneration > 0 &&
|
||||
private bool ValidCore(ProjectedNodeProof proof, bool requireLease = true) => proof.Generation > 0 &&
|
||||
(requireLease ? proof.Lease.IsValid : proof.Lease is BoundProjectionLease { Renewable: true }) && proof.Lease.Serving.ServingGeneration > 0 &&
|
||||
proof.Subject.Serving == proof.Lease.Serving && proof.Metadata.View == proof.Subject.View &&
|
||||
proof.Metadata.Serving == proof.Lease.Serving && proof.OriginMetadata.Serving == proof.Lease.Serving &&
|
||||
proof.OriginMetadata.View.MappingId is null && proof.OriginMetadata.View.MappingRevision == 0 &&
|
||||
@@ -488,6 +489,26 @@ public sealed class ProjectedCatalogCache
|
||||
proof = null; return false;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// #922: the retained, non-retired proof of a node whose authority may be refreshed by an exact renewal — a valid one,
|
||||
/// or one that is invalid ONLY because its lease lapsed (time, or a replaced route) while every local fence still holds
|
||||
/// (<see cref="BoundProjectionLease.Renewable"/>). Never an authorization: the caller still authorizes the subject and
|
||||
/// the renewal re-proves everything at the origin before anything is served.
|
||||
/// </summary>
|
||||
internal bool TryResolveForRenewal(DataRealm realm, string localId, out ProjectedNodeProof? proof)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
if (_nodes.TryGetValue((realm, localId), out var entry) && !entry.Retired && (Valid(entry.Proof) || Renewable(entry.Proof)))
|
||||
{ proof = entry.Proof; return true; }
|
||||
proof = null; return false;
|
||||
}
|
||||
}
|
||||
private bool Renewable(ProjectedNodeProof proof)
|
||||
{
|
||||
try { return ValidCore(proof, requireLease: false); }
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NullReferenceException) { return false; }
|
||||
}
|
||||
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin)
|
||||
{
|
||||
lock (_sync)
|
||||
|
||||
@@ -93,7 +93,7 @@ public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedC
|
||||
/// <summary>
|
||||
/// Retained managed bytes per imported condition, measured by the A3 L2 harness (1,000 conditions in one mapping on a
|
||||
/// running SDK 2.0.1 server: node + children + ids + registry/indexes + EventId registry + verdict cache; X0's
|
||||
/// node-only harness measured 160,997). A3b review S5: the WORST case — two placements, every EventId slot, three
|
||||
/// node-only harness retains 79,085 B on the same method, #929 — its original 160,997 was a <c>GC.GetTotalMemory</c> delta). A3b review S5: the WORST case — two placements, every EventId slot, three
|
||||
/// event items, the runner's Live + Buffer records. A3 review round 2: measured with the retained heap
|
||||
/// (<c>GCMemoryInfo</c>, not <c>GC.GetTotalMemory</c>, which counted ~125 MiB of committed-but-free regions) and the
|
||||
/// settled working set, 8 EventId slots (§5.6): max of three runs = 158,629 B (working set; heap 111,715 B), rounded up.
|
||||
|
||||
@@ -19,6 +19,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
public TimeProvider Clock { get; }
|
||||
internal Func<TimeSpan, TimeSpan>? RetryJitterForTests { get; set; }
|
||||
internal Action? BeforeSuccessorAdoptionForTests { get; set; }
|
||||
/// <summary>#920: runs on the stream pump after a publish passed its demand check, before the duplicate-baseline check.</summary>
|
||||
internal Action<IProjectedDemandLease>? AfterPublishDemandCheckForTests { get; set; }
|
||||
private readonly IFederatedProjectionCatalog _catalog;
|
||||
private readonly IProjectedNodeLookup _nodes;
|
||||
private readonly Func<string, string?> _connectionForMapping;
|
||||
@@ -201,6 +203,123 @@ 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 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);
|
||||
/// <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;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task<bool>? 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;
|
||||
try
|
||||
{
|
||||
// The SDK node must still be live, and either it or its catalog proof must have lapsed — a refusal of a node whose
|
||||
// authority is fully current was a real refusal (grant, capacity…), never a lapse.
|
||||
if (!_nodes.TryResolveForRenewal(nodeId, out var definition) || definition is null || !definition.Lifetime.IsActive ||
|
||||
!resolver.TryResolveForRenewal(definition.Realm, definition.LocalIdentifier, out var proof) || proof is null ||
|
||||
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 == DataOperations.HistoryRead && (!definition.Historizing || !ProjectedHistoryAccess.Advertises(proof))))
|
||||
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.
|
||||
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, operation);
|
||||
var budget = new DataBudget(LapseRenewalTimeout, 1, Math.Min(LapseRenewalBytes, _limits.MaxUnaryBytes));
|
||||
TaskCompletionSource<bool> 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 (now < until) return ProjectedLapseOutcome.Unavailable;
|
||||
_lapseRenewalBackoff.Remove(key);
|
||||
}
|
||||
if (_lapseRenewals.Count >= MaxQueuedLapseRenewals) return ProjectedLapseOutcome.Unavailable;
|
||||
started = new TaskCompletionSource<bool>(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));
|
||||
renewal = started.Task;
|
||||
return ProjectedLapseOutcome.Renewing;
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return ProjectedLapseOutcome.Denied; }
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
var renewed = false;
|
||||
try
|
||||
{
|
||||
renewed = await resolver.RenewExactAsync(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; }
|
||||
finally
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
_lapseRenewals.Remove(key);
|
||||
if (!renewed && !_disposed)
|
||||
{
|
||||
if (_lapseRenewalBackoff.Count >= MaxLapseRenewalBackoffEntries) EvictLapseBackoffLocked();
|
||||
var delay = (long)(LapseRenewalBackoff.TotalSeconds * Clock.TimestampFrequency);
|
||||
_lapseRenewalBackoff[key] = Clock.GetTimestamp() + Math.Max(1, delay);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
// 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)
|
||||
{
|
||||
demand = null;
|
||||
@@ -568,7 +687,11 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
internal bool HasFreshCachedLocked(Demand demand)
|
||||
{
|
||||
var sample = _cachedSample;
|
||||
if (sample is null || _cachedVersion != LastVersion || !sample.SourceProof.IsValid || !demand.IsValid || !IsValid) return false;
|
||||
// #920: deliberately NOT gated on demand.IsValid. This answers "is the sample already published for this version
|
||||
// still fresh at this demand's age limit" — the duplicate-baseline suppression in Publish. A demand disposed
|
||||
// concurrently (a failed SDK item construction) used to turn the answer into "not fresh", so a dying
|
||||
// registration re-published the same acquisition as a new complete baseline to every item on the node.
|
||||
if (sample is null || _cachedVersion != LastVersion || !sample.SourceProof.IsValid || !IsValid) return false;
|
||||
try
|
||||
{
|
||||
return sample.OriginAgeBounds.Advance(_owner.Clock.GetElapsedTime(sample.ReceivedTimestamp,
|
||||
@@ -1658,6 +1781,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
{
|
||||
validated = false;
|
||||
if (registration.Removed || !registration.Demand.IsValid || update.SourceProof is not AttemptProof proof) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishDemand); return false; }
|
||||
_owner.AfterPublishDemandCheckForTests?.Invoke(registration.Demand);
|
||||
var source = proof.Source;
|
||||
if (!source.TryPrepareSuccessor(registration.Demand, out var successor)) return false;
|
||||
try
|
||||
@@ -1675,6 +1799,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
validated = update.IsCompleteSnapshot;
|
||||
if (version == source.LastVersion && update.IsCompleteSnapshot && !registration.Recovery &&
|
||||
source.HasFreshCachedLocked(registration.Demand)) return false;
|
||||
// A demand disposed since the check above publishes nothing (it is no longer anyone's subscription).
|
||||
if (!registration.Demand.IsValid) { validated = false; ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishDemand); return false; }
|
||||
if (_owner._publisher.TryPublish([update]))
|
||||
{
|
||||
if (successor is not null)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -98,6 +104,8 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) => _cache.TryResolveProjected(realm, localId, out proof);
|
||||
public bool IsUsableProof(ProjectedNodeProof proof) => _cache.IsUsableProof(proof);
|
||||
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) => _cache.TryPinProjected(realm, localId, out pin);
|
||||
internal bool TryResolveForRenewal(DataRealm realm, string localId, out ProjectedNodeProof? proof) =>
|
||||
_cache.TryResolveForRenewal(realm, localId, out proof);
|
||||
internal bool TryPinExpiredRecoveryPair(ProjectedNodeProof previous, ProjectedNodeProof successor, out IDisposable? pin) =>
|
||||
_cache.TryPinExpiredRecoveryPair(previous, successor, out pin);
|
||||
public async Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken)
|
||||
@@ -301,8 +309,14 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
// 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)
|
||||
IProjectedNamespacePageSink sink, DataBudget budget, Func<bool> demandActive, CancellationToken cancellationToken, bool overlap = false,
|
||||
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.
|
||||
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;
|
||||
var mapping = previous.Metadata.View.MappingId;
|
||||
if (mapping is null || previous.Subject.Scope.Segments.Count == 0) return false;
|
||||
ProjectedMappingBinding binding;
|
||||
@@ -313,7 +327,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
bool CallerAllowed() => demandActive() && (configured is not null
|
||||
? configured.Matches(mapping, previous.Metadata.View, binding.LocalAuthority)
|
||||
: caller is not null && _policy.IsCallerUsable(caller) &&
|
||||
_policy.AuthorizeLocal(caller, OpcUaOperation.CreateMonitoredItems, previous.Subject.Scope));
|
||||
_policy.AuthorizeLocal(caller, authorizeAs, previous.Subject.Scope));
|
||||
if (!IsCurrent(binding) || !binding.LocalAuthority.IsActive || !CallerAllowed() ||
|
||||
previous.Metadata.View.MappingRevision != binding.Mapping.Revision || previous.Metadata.View.Realm != binding.Mapping.Realm ||
|
||||
previous.OriginMetadata.View.MappingId is not null ||
|
||||
@@ -322,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
|
||||
{
|
||||
@@ -356,7 +380,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
metadata.ValueKind != previous.OriginMetadata.ValueKind || metadata.ValueRank != previous.OriginMetadata.ValueRank ||
|
||||
metadata.ArrayElementKind != previous.OriginMetadata.ArrayElementKind ||
|
||||
!metadata.Dimensions.SequenceEqual(previous.OriginMetadata.Dimensions) ||
|
||||
(metadata.AllowedOperations & binding.Mapping.AllowedOperations & DataOperations.Subscribe) == 0 ||
|
||||
(metadata.AllowedOperations & binding.Mapping.AllowedOperations & required) == 0 ||
|
||||
!IsCurrent(binding) || !CallerAllowed() || connection.CancellationToken.IsCancellationRequested) return false;
|
||||
metadata.Validate(); remoteLease.Validate();
|
||||
var generation = _cache.CaptureGeneration(mapping);
|
||||
@@ -377,7 +401,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
var renewed = new ProjectedNodeProof(previous.LocalIdentifier, mapped, subject, resolver, lease, generation, metadata,
|
||||
TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds));
|
||||
var guard = new ExactAuthority(renewed);
|
||||
if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, OpcUaOperation.CreateMonitoredItems,
|
||||
if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, authorizeAs,
|
||||
mapped.View, serving, subject, resolver, lease)) return false;
|
||||
var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent,
|
||||
mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime, Historizing = ProjectedHistoryAccess.Advertises(renewed) };
|
||||
@@ -400,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()
|
||||
|
||||
@@ -213,6 +213,31 @@ public sealed partial class DriverHostActor
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.Args.Withdrawn)
|
||||
{
|
||||
// #926: the source lost events after establishing these conditions. Take "known" back (same chain as its
|
||||
// projections, so it lands after them), keep them out of the backstop (which would re-mark them known by
|
||||
// timer), and put them back in the F5 window so a source that never re-signals is diagnosed.
|
||||
t.Unsignalable.ExceptWith(msg.Args.ConditionIds);
|
||||
var withdrawn = MarkDriverConditionsKnown(msg.DriverInstanceId, msg.Args.ConditionIds, known: false);
|
||||
if (t.GoodSinceUtc is not null && _alarmRefsByDriver.TryGetValue(msg.DriverInstanceId, out var owned))
|
||||
{
|
||||
var ownedPaths = owned.Select(r => r.RawPath).ToHashSet(StringComparer.Ordinal);
|
||||
var before = t.Pending.Count;
|
||||
t.Pending.UnionWith(msg.Args.ConditionIds.Where(ownedPaths.Contains));
|
||||
// An F5 window already running covers them; otherwise start one now. A diagnostic already raised for
|
||||
// that window must count them too (#926 review r2).
|
||||
if (t.Pending.Count != before)
|
||||
{
|
||||
if (t.PendingSinceUtc is null) ArmSignalTimeout(msg.DriverInstanceId, t);
|
||||
else if (t.DiagnosticRaised) _conditionSignals.Hub?.UpdateUnsignalled(msg.DriverInstanceId, t.Pending.Count);
|
||||
}
|
||||
}
|
||||
_log.Info("DriverHost {Node}: driver {Driver} withdrew {Count} condition(s) ({Routed} routed) — state no longer known (events lost)",
|
||||
_localNode, msg.DriverInstanceId, msg.Args.ConditionIds.Count, withdrawn);
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.Args.Unsignalable)
|
||||
{
|
||||
// InitialStateUnsignalable: no real signal will come. Only a driver type with a backstop (OpcUaClient) marks
|
||||
@@ -327,7 +352,7 @@ public sealed partial class DriverHostActor
|
||||
}
|
||||
|
||||
/// <summary>Route driver condition ids (RawPaths) to their condition nodes and send one mark per realm.</summary>
|
||||
private int MarkDriverConditionsKnown(string driverInstanceId, IReadOnlyCollection<string> conditionIds)
|
||||
private int MarkDriverConditionsKnown(string driverInstanceId, IReadOnlyCollection<string> conditionIds, bool known = true)
|
||||
{
|
||||
if (_opcUaPublishActor is null || conditionIds.Count == 0) return 0;
|
||||
var byRealm = new Dictionary<AddressSpaceRealm, List<string>>();
|
||||
@@ -344,7 +369,7 @@ public sealed partial class DriverHostActor
|
||||
var count = 0;
|
||||
foreach (var (realm, ids) in byRealm)
|
||||
{
|
||||
_opcUaPublishActor.Tell(new PublishActor.MarkConditionsKnown(driverInstanceId, ids, realm));
|
||||
_opcUaPublishActor.Tell(new PublishActor.MarkConditionsKnown(driverInstanceId, ids, realm, Known: known));
|
||||
count += ids.Count;
|
||||
}
|
||||
|
||||
|
||||
@@ -3121,7 +3121,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
/// <see cref="HandleArtifactForApply"/>, the continuation both modes share.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Both begin-paths arm the <see cref="ApplyWedgeTimerKey"/> watchdog, because both leave the
|
||||
/// Both begin-paths arm the <see cref="ApplyWedgeTimerKey"/> watchdog — after the synchronous
|
||||
/// Applying-row write, immediately before the read/fetch starts — because both leave the
|
||||
/// host alive and dequeuing while it waits for bytes it does not have yet — which is exactly
|
||||
/// what makes a silent wedge possible. (Before the Direct read moved off the mailbox this was
|
||||
/// the only such path: an inline read could not be "stuck in Applying" in any sense a watchdog
|
||||
@@ -3131,7 +3132,6 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
{
|
||||
_applyingDeploymentId = deploymentId;
|
||||
Become(Applying);
|
||||
Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout);
|
||||
|
||||
// Persist Applying row (idempotent on PK) — same crash-boundary marker as the Direct apply.
|
||||
UpsertNodeDeploymentState(deploymentId, NodeDeploymentStatus.Applying, failureReason: null);
|
||||
@@ -3152,6 +3152,12 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
_log.Debug("DriverHost {Node}: fetching artifact for {Id} (rev {Rev}) from central over gRPC",
|
||||
_localNode, deploymentId, revision);
|
||||
|
||||
// Armed only now, AFTER the synchronous Applying-row write above and immediately before the
|
||||
// read/fetch starts: the watchdog times the read/fetch (its Warning says so), and a slow row write
|
||||
// armed-before enqueued the tick ahead of the fetch's pipe-back, reporting a fetch that answered at
|
||||
// once as WEDGED (Runtime.Tests master failures: ACompletedApply_NeverReportsAWedge on a cold EF model).
|
||||
Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout);
|
||||
|
||||
// A faulted fetch task maps to null bytes — the apply-failure path, exactly like an
|
||||
// all-endpoints-down fetch — so a fault can never escape as an unhandled actor message.
|
||||
_artifactFetcher.FetchAsync(deploymentId.ToString(), revision.Value, CancellationToken.None)
|
||||
@@ -3190,7 +3196,6 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
{
|
||||
_applyingDeploymentId = deploymentId;
|
||||
Become(Applying);
|
||||
Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout);
|
||||
|
||||
// Persist Applying row (idempotent on PK) — the crash-boundary marker, and deliberately still
|
||||
// on the actor thread: one bounded row write, and the apply must be recorded as in flight
|
||||
@@ -3200,6 +3205,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
_log.Debug("DriverHost {Node}: reading artifact for {Id} (rev {Rev}) from the ConfigDb, off the mailbox",
|
||||
_localNode, deploymentId, revision);
|
||||
|
||||
// Armed after the Applying-row write, immediately before the read starts — see BeginFetchAndCacheApply.
|
||||
Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout);
|
||||
|
||||
Task.Run(() => LoadArtifactBlob(deploymentId))
|
||||
.PipeTo(
|
||||
Self,
|
||||
|
||||
@@ -238,7 +238,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// <see cref="AttributeAlarmPublished"/>, so it reaches <see cref="DriverHostActor"/> after every alarm event the
|
||||
/// driver raised before it.</summary>
|
||||
/// <remarks>A1 review S2: <paramref name="ConnectionEpoch"/> is the connection (Connected entry) the driver raised
|
||||
/// it under, matching <see cref="ConnectivityChanged.ConnectionEpoch"/> of that Good edge.</remarks>
|
||||
/// it under, matching <see cref="ConnectivityChanged.ConnectionEpoch"/> of that Good edge. #926: keep this message
|
||||
/// IN-PROCESS (child → parent only) — it carries <see cref="AlarmInitialStateEventArgs"/> by reference, and a
|
||||
/// serialized copy that dropped <c>Withdrawn</c> would default it to false and turn a withdrawal into a "known" mark.</remarks>
|
||||
public sealed record AlarmInitialStatePublished(string DriverInstanceId, AlarmInitialStateEventArgs Args,
|
||||
long? ConnectionEpoch = null);
|
||||
private sealed record NativeAlarmInitialState(AlarmInitialStateEventArgs Args, long Epoch);
|
||||
|
||||
@@ -1165,47 +1165,89 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying {Count} deferred status writes threw", statuses.Count); }
|
||||
}
|
||||
|
||||
// G3 pre-pass: a deferred projection outside the applied scope is skipped — its source's KNOWN marks are discarded
|
||||
// wherever they sit in the arrival order (the conservative reading of "never known over a projection that did
|
||||
// not land").
|
||||
foreach (var (alarm, _) in _deferred.Alarms)
|
||||
if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) _deferred.NoteAlarmLoss(alarm.Source);
|
||||
|
||||
// #926 review r2: alarm states, alarm qualities and condition-known marks replay as ONE list in ARRIVAL order.
|
||||
// Marks used to replay after every alarm, which was right for a "known" mark (it summarises the projections
|
||||
// before it) but wrong for a withdrawal followed by a live transition: replayed transition-then-withdrawal,
|
||||
// the condition ended unknown although the transition had re-established it — and the host, which saw the
|
||||
// transition last, no longer counted it in F5. Arrival order is exactly what the live path applies.
|
||||
var items = new List<(long Seq, int Kind, int Index)>();
|
||||
var alarmList = _deferred.Alarms.ToList();
|
||||
var qualityList = _deferred.AlarmQualities.ToList();
|
||||
var markList = _deferred.Marks.ToList();
|
||||
for (var i = 0; i < alarmList.Count; i++) items.Add((alarmList[i].Seq, 0, i));
|
||||
for (var i = 0; i < qualityList.Count; i++) items.Add((qualityList[i].Seq, 1, i));
|
||||
for (var i = 0; i < markList.Count; i++) items.Add((markList[i].Seq, 2, i));
|
||||
items.Sort((x, y) => x.Seq.CompareTo(y.Seq));
|
||||
|
||||
var alarms = 0;
|
||||
foreach (var alarm in _deferred.Alarms)
|
||||
{
|
||||
if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId)))
|
||||
{
|
||||
_deferred.NoteAlarmLoss(alarm.Source); // G3: a skipped projection — the source's marks go too
|
||||
continue;
|
||||
}
|
||||
|
||||
alarms++;
|
||||
try { _sink.WriteAlarmCondition(alarm.AlarmNodeId, alarm.State, alarm.TimestampUtc, alarm.Realm, alarm.EstablishesState); }
|
||||
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); }
|
||||
}
|
||||
|
||||
var qualities = 0;
|
||||
foreach (var quality in _deferred.AlarmQualities)
|
||||
{
|
||||
if (!scope.Conditions.Contains((quality.Realm, quality.AlarmNodeId))) continue;
|
||||
qualities++;
|
||||
try { _sink.WriteAlarmQuality(quality.AlarmNodeId, quality.StatusCode, quality.TimestampUtc, quality.Realm); }
|
||||
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm-quality write threw for {Node}", quality.AlarmNodeId); }
|
||||
}
|
||||
|
||||
// A1 F2/G3: the deferred "known" marks replay LAST, after every deferred alarm — and only for a source none of
|
||||
// whose deferred projections was dropped or skipped. A discarded mark leaves its conditions unknown (Uncertain)
|
||||
// until the source's next signal.
|
||||
var marks = 0;
|
||||
var discarded = 0;
|
||||
foreach (var (mark, sender) in _deferred.Marks)
|
||||
var discardedBySender = new Dictionary<(string Source, AddressSpaceRealm Realm), (IActorRef? Sender, List<string> Ids)>();
|
||||
// Consecutive marks of one (source, realm, known) are applied as one sink call.
|
||||
string? runSource = null;
|
||||
AddressSpaceRealm runRealm = default;
|
||||
var runKnown = false;
|
||||
var runIds = new List<string>();
|
||||
void FlushRun()
|
||||
{
|
||||
// A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe.
|
||||
if (mark.Known && _deferred.SourceLost(mark.Source))
|
||||
if (runIds.Count == 0) return;
|
||||
marks++;
|
||||
ApplyMark(new MarkConditionsKnown(runSource!, runIds.ToList(), runRealm, runKnown));
|
||||
runIds.Clear();
|
||||
}
|
||||
|
||||
foreach (var (_, kind, index) in items)
|
||||
{
|
||||
if (kind == 2)
|
||||
{
|
||||
discarded++;
|
||||
TellDiscarded(sender, new ConditionMarksDiscarded(mark.Source, mark.ConditionIds, mark.Realm));
|
||||
var m = markList[index];
|
||||
// A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe.
|
||||
if (m.Known && _deferred.SourceLost(m.Source))
|
||||
{
|
||||
discarded++;
|
||||
if (!discardedBySender.TryGetValue((m.Source, m.Realm), out var d))
|
||||
discardedBySender[(m.Source, m.Realm)] = d = (m.Sender, new List<string>());
|
||||
d.Ids.Add(m.ConditionId);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (runIds.Count > 0 && (runSource != m.Source || runRealm != m.Realm || runKnown != m.Known)) FlushRun();
|
||||
runSource = m.Source;
|
||||
runRealm = m.Realm;
|
||||
runKnown = m.Known;
|
||||
runIds.Add(m.ConditionId);
|
||||
continue;
|
||||
}
|
||||
|
||||
marks++;
|
||||
ApplyMark(mark);
|
||||
FlushRun();
|
||||
if (kind == 0)
|
||||
{
|
||||
var alarm = alarmList[index].Msg;
|
||||
if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) continue; // counted in the pre-pass
|
||||
alarms++;
|
||||
try { _sink.WriteAlarmCondition(alarm.AlarmNodeId, alarm.State, alarm.TimestampUtc, alarm.Realm, alarm.EstablishesState); }
|
||||
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); }
|
||||
}
|
||||
else
|
||||
{
|
||||
var quality = qualityList[index].Msg;
|
||||
if (!scope.Conditions.Contains((quality.Realm, quality.AlarmNodeId))) continue;
|
||||
qualities++;
|
||||
try { _sink.WriteAlarmQuality(quality.AlarmNodeId, quality.StatusCode, quality.TimestampUtc, quality.Realm); }
|
||||
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm-quality write threw for {Node}", quality.AlarmNodeId); }
|
||||
}
|
||||
}
|
||||
FlushRun();
|
||||
|
||||
foreach (var ((source, realm), (sender, ids)) in discardedBySender)
|
||||
TellDiscarded(sender, new ConditionMarksDiscarded(source, ids, realm));
|
||||
|
||||
// N1: a KNOWN mark that did not fit the deferral was dropped (staying unknown is safe) — its sender hears it.
|
||||
foreach (var (source, sender) in _deferred.OverflowedMarkSources)
|
||||
@@ -1233,6 +1275,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
/// the two live writes leave on the node). Bounded by <see cref="Capacity"/> distinct keys across all kinds;
|
||||
/// beyond it a NEW key is not held (an existing key still updates), counted in <see cref="Dropped"/>.
|
||||
/// </summary>
|
||||
/// <summary>One deferred condition-known mark (#926 review r2: per condition, with its arrival sequence).</summary>
|
||||
private sealed record DeferredMark(
|
||||
string Source, string ConditionId, AddressSpaceRealm Realm, bool Known, IActorRef? Sender, long Seq);
|
||||
|
||||
private sealed class DeferredWrites(int capacity)
|
||||
{
|
||||
private struct VariableEntry
|
||||
@@ -1246,11 +1292,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
}
|
||||
|
||||
private readonly Dictionary<(AddressSpaceRealm, string), VariableEntry> _variables = new();
|
||||
private readonly Dictionary<(AddressSpaceRealm, string), AlarmStateUpdate> _alarms = new();
|
||||
private readonly Dictionary<(AddressSpaceRealm, string), AlarmQualityUpdate> _qualities = new();
|
||||
// A1: condition-known marks in arrival order (bounded by Capacity — a dropped mark only keeps conditions
|
||||
// unknown, which is always safe), and the sources that lost a deferred alarm projection (G3).
|
||||
private readonly List<(MarkConditionsKnown Msg, IActorRef? Sender)> _marks = new();
|
||||
private readonly Dictionary<(AddressSpaceRealm, string), (AlarmStateUpdate Msg, long Seq)> _alarms = new();
|
||||
private readonly Dictionary<(AddressSpaceRealm, string), (AlarmQualityUpdate Msg, long Seq)> _qualities = new();
|
||||
// A1 / #926 review r2: the LATEST condition-known mark per (realm, condition id), with its arrival sequence, and
|
||||
// the sources that lost a deferred alarm projection (G3). Per-condition, so a withdrawal-heavy plan window holds
|
||||
// at most one entry per condition (bounded by the address space), and replay can interleave marks with alarm
|
||||
// states in arrival order.
|
||||
private readonly Dictionary<(AddressSpaceRealm, string), DeferredMark> _marks = new();
|
||||
private long _seq;
|
||||
private readonly Dictionary<string, IActorRef?> _overflowedMarkSources = new(StringComparer.Ordinal);
|
||||
private readonly HashSet<string> _lossySources = new(StringComparer.Ordinal);
|
||||
private bool _unattributedLoss;
|
||||
@@ -1259,20 +1308,31 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
public long Dropped { get; private set; }
|
||||
public int Count => _variables.Count + _alarms.Count + _qualities.Count;
|
||||
public bool IsEmpty => Count == 0 && _marks.Count == 0;
|
||||
public IEnumerable<AlarmStateUpdate> Alarms => _alarms.Values;
|
||||
public IEnumerable<AlarmQualityUpdate> AlarmQualities => _qualities.Values;
|
||||
public IReadOnlyList<(MarkConditionsKnown Msg, IActorRef? Sender)> Marks => _marks;
|
||||
public IEnumerable<(AlarmStateUpdate Msg, long Seq)> Alarms => _alarms.Values;
|
||||
public IEnumerable<(AlarmQualityUpdate Msg, long Seq)> AlarmQualities => _qualities.Values;
|
||||
public IEnumerable<DeferredMark> Marks => _marks.Values;
|
||||
|
||||
/// <summary>
|
||||
/// Defer a mark. A withdrawal (<c>Known: false</c>) is never dropped — review round 2 N1: staying KNOWN over a
|
||||
/// lost withdrawal is the unsafe direction, and withdrawals are bounded by connectivity edges. A known mark
|
||||
/// beyond <see cref="Capacity"/> is dropped (unknown is safe) and its source is remembered so the sender hears
|
||||
/// of it at replay (N2).
|
||||
/// Defer a mark, per condition: a later mark of the same condition replaces the earlier (the later one is what
|
||||
/// the live path leaves). A withdrawal (<c>Known: false</c>) is never dropped — review round 2 N1: staying KNOWN
|
||||
/// over a lost withdrawal is the unsafe direction. It is bounded anyway: one entry per condition, so at most
|
||||
/// the number of conditions in the address space (#926 made withdrawals routine, so the old "bounded by
|
||||
/// connectivity edges" no longer held). A known mark for a NEW condition beyond <see cref="Capacity"/> marks is
|
||||
/// dropped (unknown is safe) and its source is remembered so the sender hears of it at replay (N2).
|
||||
/// </summary>
|
||||
public void Mark(MarkConditionsKnown msg, IActorRef? sender)
|
||||
{
|
||||
if (!msg.Known || _marks.Count < Capacity) _marks.Add((msg, sender));
|
||||
else _overflowedMarkSources[msg.Source] = sender;
|
||||
foreach (var id in msg.ConditionIds)
|
||||
{
|
||||
if (string.IsNullOrEmpty(id)) continue;
|
||||
var key = (msg.Realm, id);
|
||||
if (msg.Known && !_marks.ContainsKey(key) && _marks.Count >= Capacity)
|
||||
{
|
||||
_overflowedMarkSources[msg.Source] = sender;
|
||||
continue;
|
||||
}
|
||||
_marks[key] = new DeferredMark(msg.Source, id, msg.Realm, msg.Known, sender, ++_seq);
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<(string Source, IActorRef? Sender)> OverflowedMarkSources =>
|
||||
@@ -1325,12 +1385,18 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
public bool Alarm(AlarmStateUpdate msg)
|
||||
{
|
||||
var key = (msg.Realm, msg.AlarmNodeId);
|
||||
if (!Put(_alarms, key, msg)) return false;
|
||||
if (!Put(_alarms, key, (msg, _seq + 1))) return false;
|
||||
_seq++;
|
||||
_qualities.Remove(key);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool AlarmQuality(AlarmQualityUpdate msg) => Put(_qualities, (msg.Realm, msg.AlarmNodeId), msg);
|
||||
public bool AlarmQuality(AlarmQualityUpdate msg)
|
||||
{
|
||||
if (!Put(_qualities, (msg.Realm, msg.AlarmNodeId), (msg, _seq + 1))) return false;
|
||||
_seq++;
|
||||
return true;
|
||||
}
|
||||
|
||||
public (List<ValueWrite> Values, List<StatusWrite> Statuses) VariableWrites(Func<(AddressSpaceRealm, string), bool> include)
|
||||
{
|
||||
@@ -1357,6 +1423,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
_lossySources.Clear();
|
||||
_unattributedLoss = false;
|
||||
Dropped = 0;
|
||||
_seq = 0;
|
||||
}
|
||||
|
||||
private bool Put<T>(Dictionary<(AddressSpaceRealm, string), T> map, (AddressSpaceRealm, string) key, T value)
|
||||
|
||||
Reference in New Issue
Block a user