feat: expose mapped raw and uns data through grpc adapters

This commit is contained in:
Joseph Doherty
2026-11-16 20:43:15 -05:00
parent 47960a6d57
commit 8ad03e9c5d
118 changed files with 12645 additions and 227 deletions
@@ -9,6 +9,7 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Host.Grpc;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
@@ -62,6 +63,67 @@ public static class DataConnectionRegistration
() => sp.GetRequiredService<LocalCatalogCoordinator>().Serving, sp.GetRequiredService<DataConnectionProcessIdentity>().ClusterId));
services.AddSingleton(sp => new DataOperationPolicy(sp.GetRequiredService<DataPlaneAuthorityState>(),
sp.GetRequiredService<IPermissionEvaluator>(), sp.GetRequiredService<TimeProvider>()));
services.AddSingleton<DeployedGrpcDataConnectionSource>();
services.AddSingleton<IGrpcDataAdapterConnectionSource>(sp => sp.GetRequiredService<DeployedGrpcDataConnectionSource>());
services.AddSingleton(sp => new ProjectedCatalogCache(options.MaxMonitoredItems, options.Hub.MaxTrackedSources,
sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<DataOperationPolicy>(), options.MaxTransportBytes));
services.AddSingleton(sp => new BrowseContinuationRegistry(options.MaxMonitoredItems, sp.GetRequiredService<TimeProvider>()));
services.AddSingleton(sp => new RemoteNamespaceResolver(sp.GetRequiredService<ProjectedCatalogCache>(),
sp.GetRequiredService<BrowseContinuationRegistry>(), sp.GetRequiredService<IGrpcDataAdapterConnectionSource>(),
sp.GetRequiredService<DataOperationPolicy>(), 256, options.MaxConcurrentCalls));
services.AddSingleton<IFederatedProjectionCatalog>(sp => sp.GetRequiredService<RemoteNamespaceResolver>());
services.AddSingleton<ProjectedMappingDeploymentRuntime>();
services.TryAddSingleton<DeferredAddressSpaceSink>();
services.AddSingleton<DeferredProjectedNodeAccess>();
services.AddSingleton<IProjectedNodeLookup>(sp => sp.GetRequiredService<DeferredProjectedNodeAccess>());
services.AddSingleton<IProjectedAnchorSink>(sp => sp.GetRequiredService<DeferredProjectedNodeAccess>());
services.AddSingleton<IProjectedNamespacePageSink, DeferredProjectedNamespacePageSink>();
services.AddSingleton(sp => new ProjectedNamespaceApplier(sp.GetRequiredService<IFederatedProjectionCatalog>(),
sp.GetRequiredService<IProjectedNamespacePageSink>(), options.MaxConcurrentCalls));
services.AddSingleton(sp => new ProjectedBrowseAccess(sp.GetRequiredService<ProjectedMappingDeploymentRuntime>(),
sp.GetRequiredService<IFederatedProjectionCatalog>(), sp.GetRequiredService<ProjectedNamespaceApplier>(),
sp.GetRequiredService<IProjectedAnchorSink>(), (uri, identifier) =>
sp.GetRequiredService<IProjectedNodeLookup>().TryGetNodeId(uri, identifier, out var nodeId) ? nodeId : null,
new DataBudget(options.UnaryTimeout, 1000, options.MaxMessageBytes), options.MaxConcurrentCalls));
services.AddSingleton<IProjectedBrowseAccess>(sp => sp.GetRequiredService<ProjectedBrowseAccess>());
services.AddSingleton(sp => new ActorProjectedValuePublisher(
() => sp.GetService<ActorRegistry>() is { } registry && registry.TryGet<DriverHostActorKey>(out var host) ? host : null,
route =>
{
var catalog = sp.GetRequiredService<IFederatedProjectionCatalog>();
var mappings = sp.GetRequiredService<ProjectedMappingDeploymentRuntime>();
return catalog.TryResolveProjected(route.Realm, route.LocalIdentifier, out var proof) && proof is not null
&& proof.Generation == route.ProjectionGeneration && proof.Lease.IsValid && proof.Lease.Serving == route.Serving
&& proof.Metadata.View.MappingId is { } mappingId && mappings.TryGetConnectionId(mappingId, out var connectionId)
&& route.DriverInstanceId == "grpc-data:" + connectionId;
}, options.MaxMonitoredItems, options.MaxPendingBytes, sp.GetRequiredService<TimeProvider>(), options.MaxTransportBytes));
services.AddSingleton<IProjectedValuePublisher>(sp => sp.GetRequiredService<ActorProjectedValuePublisher>());
services.AddSingleton(sp => new ProjectedDataAccess(sp.GetRequiredService<IFederatedProjectionCatalog>(),
sp.GetRequiredService<IProjectedNodeLookup>(), sp.GetRequiredService<IGrpcDataAdapterConnectionSource>(),
mappingId => sp.GetRequiredService<ProjectedMappingDeploymentRuntime>().TryGetConnectionId(mappingId, out var connectionId)
? connectionId : null,
sp.GetRequiredService<DataOperationPolicy>(), sp.GetRequiredService<IProjectedValuePublisher>(),
sp.GetRequiredService<TimeProvider>(),
new(options.MaxMonitoredItems, options.MaxConcurrentCalls, options.MaxPendingBytes, options.MaxStreams),
localWriteRole: () =>
{
var role = sp.GetRequiredService<RedundancyRoleView>();
var state = CaptureRole(role, sp.GetRequiredService<DataConnectionWarmRoleView>());
var settings = sp.GetService<WarmRedundancySettings>() ?? WarmRedundancySettings.Unset;
var active = sp.GetRequiredService<LocalCatalogCoordinator>().Current is { IsActive: true };
return (active && role.ShouldActAsPrimary && state.Role == "Primary" &&
(!settings.IsWarm || state.WarmRole == WarmRole.Active), state.Generation);
}));
services.AddSingleton<IProjectedDataAccess>(sp => sp.GetRequiredService<ProjectedDataAccess>());
services.AddSingleton<IConfiguredProjectionDiscovery>(sp => new ConfiguredProjectionDiscovery(
sp.GetRequiredService<ProjectedMappingDeploymentRuntime>(), sp.GetRequiredService<IFederatedProjectionCatalog>(),
sp.GetRequiredService<ProjectedNamespaceApplier>(), sp.GetRequiredService<IProjectedNodeLookup>(),
sp.GetRequiredService<ProjectedDataAccess>(),
new DataBudget(options.UnaryTimeout, Math.Min(options.MaxMonitoredItems, 1000), options.MaxMessageBytes), 256));
services.AddSingleton(sp => new ConfiguredProjectedInterestOwner(
sp.GetRequiredService<IConfiguredProjectionDiscovery>(), options.MaxMonitoredItems,
options.MaxConcurrentCalls, options.MaxTransportBytes, sp.GetRequiredService<TimeProvider>()));
services.AddSingleton<IProjectedDependencyInterestSink>(sp => sp.GetRequiredService<ConfiguredProjectedInterestOwner>());
services.AddSingleton(sp =>
{
var catalog = sp.GetRequiredService<LocalCatalogCoordinator>();
@@ -42,7 +42,7 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Engines;
/// boundary), never by itself.
/// </para>
/// </summary>
public sealed class RoslynVirtualTagEvaluator : IVirtualTagEvaluator, IScriptCacheOwner, IScriptQuarantineOwner, IDisposable
public sealed class RoslynVirtualTagEvaluator : IProjectedVirtualTagEvaluator, IScriptCacheOwner, IScriptQuarantineOwner, IDisposable
{
// Purpose-built source-hash-keyed compile cache: Lazy single-compile (no double-compile race) and
// Clear()/Dispose() that dispose each evaluator's collectible AssemblyLoadContext. The apply-boundary
@@ -135,9 +135,23 @@ public sealed class RoslynVirtualTagEvaluator : IVirtualTagEvaluator, IScriptCac
/// complete synchronously (cheap), a first-use compile is pushed to the pool, and the script run is awaited.
/// The outcomes are exactly those of the synchronous overload, which now delegates here.
/// </remarks>
public async Task<VirtualTagEvalResult> EvaluateAsync(
public Task<VirtualTagEvalResult> EvaluateAsync(
string virtualTagId, string expression, IReadOnlyDictionary<string, DataValueSnapshot> dependencies)
=> EvaluateCoreAsync(virtualTagId, expression, dependencies, null);
/// <inheritdoc />
public Task<VirtualTagEvalResult> EvaluateProjectedAsync(string virtualTagId, string expression,
IReadOnlyDictionary<string, DataValueSnapshot> dependencies, IDisposable physicalLease)
=> EvaluateCoreAsync(virtualTagId, expression, dependencies, physicalLease);
private async Task<VirtualTagEvalResult> EvaluateCoreAsync(
string virtualTagId, string expression, IReadOnlyDictionary<string, DataValueSnapshot> dependencies, IDisposable? physicalLease)
{
var ownership = new PhysicalLeaseOwnership(physicalLease);
try
{
if (physicalLease is not null && _runner is not null && _runner is not IPhysicalScriptRunner)
return VirtualTagEvalResult.Failure("runner does not support projected input ownership");
if (_disposed) return VirtualTagEvalResult.Failure("evaluator disposed");
if (string.IsNullOrWhiteSpace(expression)) return VirtualTagEvalResult.Failure("empty expression");
@@ -176,20 +190,30 @@ public sealed class RoslynVirtualTagEvaluator : IVirtualTagEvaluator, IScriptCac
// coalescer submits those as one batch (design §4.5) and an evaluation on an idle seam at once.
if (_batches is not null)
{
var outcome = await _batches.RunAsync(new ScriptInvocation(
virtualTagId, ScriptContextKind.VirtualTag, expression, readCache, _runTimeout, scriptLog)).ConfigureAwait(false);
var invocation = new ScriptInvocation(virtualTagId, ScriptContextKind.VirtualTag, expression,
readCache, _runTimeout, scriptLog, physicalLease is null ? null : ownership.Transfer());
ScriptRunOutcome outcome;
if (physicalLease is null) outcome = await _batches.RunAsync(invocation).ConfigureAwait(false);
else
{
try { outcome = await _runner!.RunAsync(invocation).ConfigureAwait(false); }
catch { ownership.Dispose(); throw; }
}
return outcome.ToVirtualTagEvalResult();
}
var result = await RunInProcessAsync(virtualTagId, expression, context).ConfigureAwait(false);
var result = await RunInProcessAsync(virtualTagId, expression, context, physicalLease is null ? null : ownership).ConfigureAwait(false);
// lmxopcua#780 P2 — Shadow: `result` is what gets published; the same evaluation is mirrored to the worker pool
// and only compared. Mirror never blocks and nothing it does reaches this result.
if (_shadow is not null && result.ToMirroredOutcome() is { } mirrored)
if (physicalLease is null && _shadow is not null && result.ToMirroredOutcome() is { } mirrored)
_shadow.Mirror(new ScriptInvocation(virtualTagId, ScriptContextKind.VirtualTag, expression, readCache, _runTimeout), mirrored);
return result;
}
finally { ownership.DisposeIfUntransferred(); }
}
private async Task<VirtualTagEvalResult> RunInProcessAsync(string virtualTagId, string expression, VirtualTagContext context)
private async Task<VirtualTagEvalResult> RunInProcessAsync(string virtualTagId, string expression, VirtualTagContext context,
PhysicalLeaseOwnership? ownership)
{
// 02/S12: fetch + run inside a bounded loop so an ObjectDisposedException caused by a concurrent
// apply-boundary ClearCompiledScripts (which disposed the evaluator between GetOrCompile and the
@@ -235,7 +259,7 @@ public sealed class RoslynVirtualTagEvaluator : IVirtualTagEvaluator, IScriptCac
// it), so the wall-clock budget is what returns control — and the guard is what stops the
// abandoned run from being joined by another on the next trigger (one orphan per tag, then
// quarantine), which is the leak the old per-evaluation TimedScriptEvaluator allowed.
var raw = await _guard.RunAsync(virtualTagId, expression, evaluator, context, _runTimeout)
var raw = await _guard.RunAsync(virtualTagId, expression, evaluator, context, _runTimeout, physicalLease: ownership?.Transfer())
.ConfigureAwait(false);
return VirtualTagEvalResult.Ok(raw);
}
@@ -252,7 +276,7 @@ public sealed class RoslynVirtualTagEvaluator : IVirtualTagEvaluator, IScriptCac
{
return VirtualTagEvalResult.Failure(ex.Message);
}
catch (ObjectDisposedException) when (!_disposed && attempt == 0)
catch (ObjectDisposedException) when (!_disposed && attempt == 0 && ownership is null)
{
// S12: the apply-boundary ClearCompiledScripts disposed the evaluator between our
// GetOrCompile and the run's disposed-guard. Re-fetch — GetOrCompile recompiles the same
@@ -22,7 +22,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
var budget = new DataBudget(_options.UnaryTimeout, 1, _options.MaxMessageBytes);
var capabilities = await connection.GetCapabilitiesAsync(budget, token).ConfigureAwait(false);
var response = DataProtoMapper.EncodeCapabilities(capabilities with
{ ProtocolMinor = Math.Max(2, capabilities.ProtocolMinor), ResponseServingIdentity = true, SubscriptionAgeReadiness = true });
{ ProtocolMinor = Math.Max(3, capabilities.ProtocolMinor), ResponseServingIdentity = true, SubscriptionAgeReadiness = true });
CheckSize(response);
var current = await connection.GetCapabilitiesAsync(budget, token).ConfigureAwait(false);
if (!authenticator.IsCurrent(caller) || current.Serving != capabilities.Serving
@@ -7,12 +7,15 @@ using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.OtOpcUa.Cluster;
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using ZB.MOM.WW.OtOpcUa.Runtime;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Historian;
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
@@ -55,6 +58,10 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
private readonly OpcUaEndpointState _endpointState;
private readonly bool _rethrowStartFailure;
private readonly DriverWriteBounds _writeBounds;
private readonly IProjectedBrowseAccess? _projectedBrowseAccess;
private readonly IProjectedDataAccess? _projectedDataAccess;
private readonly IFederatedProjectionCatalog? _projectedCatalog;
private readonly DataConnectionOptions _dataConnectionOptions;
private OpcUaApplicationHost? _appHost;
@@ -130,6 +137,9 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
/// <see cref="DriverWriteBounds.Default"/>.</param>
/// <param name="deferredStandby">The late-bound Warm standby projection (Gitea #717) <c>OpcUaPublishActor</c> drives;
/// bound here once the SDK has started. Optional: null (and a non-Warm server) binds nothing.</param>
/// <param name="projectedBrowseAccess">Optional caller-bound mapped browse scheduler.</param>
/// <param name="projectedDataAccess">Optional bounded mapped read, write and subscription gateway.</param>
/// <param name="projectedCatalog">Optional live projection catalog used for mapped authorization.</param>
public OtOpcUaServerHostedService(
IOptions<OpcUaApplicationHostOptions> options,
DeferredAddressSpaceSink deferredSink,
@@ -151,8 +161,15 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
EffectiveRoles? roles = null,
NativeAlarmAckPreflightView? ackPreflightView = null,
DriverWriteBounds? writeBounds = null,
DeferredStandbyProjection? deferredStandby = null)
DeferredStandbyProjection? deferredStandby = null,
IProjectedBrowseAccess? projectedBrowseAccess = null,
IProjectedDataAccess? projectedDataAccess = null,
IFederatedProjectionCatalog? projectedCatalog = null)
{
_dataConnectionOptions = configuration.GetSection(DataConnectionOptions.SectionName).Get<DataConnectionOptions>() ?? new();
_projectedBrowseAccess = projectedBrowseAccess;
_projectedDataAccess = projectedDataAccess;
_projectedCatalog = projectedCatalog;
_deferredStandby = deferredStandby;
ArgumentNullException.ThrowIfNull(aclOptions);
ArgumentNullException.ThrowIfNull(time);
@@ -239,7 +256,22 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
// first guarantees every node sees it (nodes are never retro-updated).
_server.SetHistorianDataUpdater(_historianUpdater.Updater);
if (_dataConnectionOptions.Enabled)
{
_server.SetProjectedBrowseLimits(_dataConnectionOptions.MaxMonitoredItems, _dataConnectionOptions.MaxTransportBytes);
_server.NodeManager.ConfigureProjectedNodeLimits(_dataConnectionOptions.MaxMonitoredItems, _dataConnectionOptions.MaxTransportBytes);
}
_server.NodeManager.ProjectedBrowseAccess = _projectedBrowseAccess;
_server.NodeManager.ProjectedBrowseClock = _time;
_server.NodeManager.ProjectedDataAccess = _projectedDataAccess;
if (_projectedCatalog is { } projectedCatalog)
_server.NodeManager.MappedSubjectResolver = (realm, identifier) =>
projectedCatalog.TryResolveProjected(realm == AddressSpaceRealm.Raw ? DataRealm.Raw : DataRealm.Uns,
identifier, out var proof) && proof is not null
? MappedNodeResolution.Mapped(proof.Metadata.View, proof.Subject, proof.Resolver, proof.Lease)
: MappedNodeResolution.Deny;
_deferredSink.SetSink(new SdkAddressSpaceSink(_server.NodeManager));
(_projectedBrowseAccess as ProjectedBrowseAccess)?.RefreshAnchors();
// Wire the reverse-path inbound-alarm-command router: a client Acknowledge/Confirm/Shelve that
// passes the node manager's AlarmAck gate publishes the mapped AlarmCommand onto the cluster
@@ -0,0 +1,17 @@
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>Resolves the currently bound SDK page sink without retaining a retired node manager.</summary>
public sealed class DeferredProjectedNamespacePageSink(DeferredAddressSpaceSink deferred) : IProjectedNamespacePageSink
{
public bool TryApply(NodeId parent, IReadOnlyList<ProjectedVariableDefinition> nodes, Func<bool> commit) =>
deferred.GetCapability<IProjectedNamespacePageSink>()?.TryApply(parent, nodes, commit) ?? false;
public bool TryApplyRootLeaf(NodeId anchorId, ProjectedVariableDefinition rootDefinition, Func<bool> commit) =>
deferred.GetCapability<IProjectedNamespacePageSink>()?.TryApplyRootLeaf(anchorId, rootDefinition, commit) ?? false;
public bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected) =>
deferred.GetCapability<IProjectedNamespacePageSink>()?.TryRemove(nodeId, expected) ?? false;
}
@@ -0,0 +1,26 @@
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>Resolves projected node capabilities from the currently bound SDK sink.</summary>
public sealed class DeferredProjectedNodeAccess(DeferredAddressSpaceSink deferred) : IProjectedNodeLookup, IProjectedAnchorSink
{
public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition)
{
definition = null;
return deferred.GetCapability<IProjectedNodeLookup>()?.TryResolve(nodeId, out definition) == true;
}
public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId)
{
nodeId = null;
return deferred.GetCapability<IProjectedNodeLookup>()?.TryGetNodeId(namespaceUri, identifier, out nodeId) == true;
}
public bool TryEnsureProjectedAnchor(ProjectedAnchorDefinition definition, out NodeId? nodeId)
{
nodeId = null;
return deferred.GetCapability<IProjectedAnchorSink>()?.TryEnsureProjectedAnchor(definition, out nodeId) == true;
}
public bool TryRemoveProjectedAnchor(NodeId nodeId, ProjectedAnchorDefinition expected) =>
deferred.GetCapability<IProjectedAnchorSink>()?.TryRemoveProjectedAnchor(nodeId, expected) == true;
}
@@ -0,0 +1,28 @@
using Opc.Ua;
using Opc.Ua.Server;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>Borrowed SDK browse state; implementations must not retain or mutate the continuation object.</summary>
public sealed record ProjectedBrowseContext(NodeId Parent, RoleCarryingUserIdentity? Caller,
ContinuationPoint Continuation, long RequestStartedTimestamp);
/// <summary>A copied, caller-bound request for one projected page.</summary>
public sealed record ProjectedBrowsePageRequest(NodeId Parent, RoleCarryingUserIdentity Caller, string? Cursor,
uint MaximumResults, long RequestStartedTimestamp);
/// <summary>An immutable page snapshot; authority must remain live through emission.</summary>
public sealed record ProjectedBrowsePage(ProjectedBrowseReadiness Status, IReadOnlyList<NodeId> Children,
string? NextCursor, bool Complete, Func<bool> IsCurrent, long RetainedBytes = 0);
/// <summary>Per-caller synchronous lookup and bounded scheduling, never network I/O.</summary>
public interface IProjectedBrowseAccess
{
ProjectedBrowseReadiness GetOrSchedule(ProjectedBrowseContext context);
ProjectedBrowsePage GetOrSchedulePage(ProjectedBrowsePageRequest request) =>
new(ProjectedBrowseReadiness.Unavailable, [], null, false, static () => false);
/// <summary>Waits for a bounded coalesced page preparation without occupying an SDK lock.</summary>
Task<ProjectedBrowsePage> WaitForPageAsync(ProjectedBrowsePageRequest request, CancellationToken cancellationToken) =>
Task.FromResult(GetOrSchedulePage(request));
}
@@ -0,0 +1,35 @@
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>A caller- and item-scoped projection demand, bound to its original local and remote authority.</summary>
public interface IProjectedDemandLease : IDisposable
{
DataView OriginView { get; }
DataRealm Realm { get; }
string LocalIdentifier { get; }
long ProjectionGeneration { get; }
/// <summary>Maximum allowed origin-cache age; zero denies sample delivery.</summary>
TimeSpan MaximumSampleAge => TimeSpan.Zero;
ServingIdentity Serving { get; }
CancellationToken CancellationToken { get; }
bool IsValid { get; }
}
/// <summary>Nonblocking local admission and bounded scheduling for projected data.</summary>
public interface IProjectedDataAccess
{
TimeProvider Clock { get; }
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);
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>True while a demand or physically retained operation still owns this projection.</summary>
bool HasLiveDemand(DataRealm realm, string localIdentifier) => true;
}
@@ -0,0 +1,12 @@
using Opc.Ua;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>Applies a prepared page atomically with its cursor commit.</summary>
public interface IProjectedNamespacePageSink
{
bool TryApply(NodeId parent, IReadOnlyList<ProjectedVariableDefinition> nodes, Func<bool> commit);
bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected);
/// <summary>Atomically promotes an owned mapping anchor to its verified leaf value.</summary>
bool TryApplyRootLeaf(NodeId anchorId, ProjectedVariableDefinition rootDefinition, Func<bool> commit) => false;
}
@@ -0,0 +1,23 @@
using Opc.Ua;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>Reports bytes retained by a projected node's detached authority guard.</summary>
public interface IProjectedRetainedAuthority
{
long RetainedBytes { get; }
}
/// <summary>Resolves against the currently live SDK node manager, without conferring authority.</summary>
public interface IProjectedNodeLookup
{
bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition);
bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId);
}
/// <summary>Installs and retires locally authorized mapping anchors.</summary>
public interface IProjectedAnchorSink
{
bool TryEnsureProjectedAnchor(ProjectedAnchorDefinition definition, out NodeId? nodeId);
bool TryRemoveProjectedAnchor(NodeId nodeId, ProjectedAnchorDefinition expected);
}
@@ -8,6 +8,15 @@ using Opc.Ua.Server;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using DataRealm = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataRealm;
using DataBudget = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataBudget;
using DataOperations = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataOperations;
using DataMetadata = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataMetadata;
using DataValueKind = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValueKind;
using ProjectedDataIds = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ProjectedDataIds;
using IProjectedValueSink = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedValueSink;
using IProjectedSamplePublicationProof = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof;
using ProjectedValueWrite = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ProjectedValueWrite;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
// The SDK's HistoryRead service result (the value the override fills + hands back) and the historian
@@ -20,6 +29,25 @@ using DataWriteState = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataW
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>Current page readiness for a projected browse parent.</summary>
public enum ProjectedBrowseReadiness { Ready, Pending, Unavailable, InvalidContinuation }
/// <summary>A checked local placement for a remotely derived variable.</summary>
public sealed record ProjectedVariableDefinition(DataRealm Realm, string LocalIdentifier, NodeId Parent,
DataMetadata Metadata, long ProjectionGeneration, Func<bool> AuthorityIsCurrent)
{
/// <summary>Stable across same-node metadata renewal, replaced on node retirement.</summary>
public ProjectedNodeLifetime Lifetime { get; init; } = new();
}
/// <summary>Locally authorized placement for a configured mapping anchor.</summary>
public sealed record ProjectedAnchorDefinition(DataRealm Realm, string LocalIdentifier, NodeId Parent,
string BrowseName, string LocalSubject, string MappingId, long MappingRevision, Func<bool> AuthorityIsCurrent)
{
/// <summary>Stable for one installed mapping anchor incarnation.</summary>
public ProjectedNodeLifetime Lifetime { get; init; } = new();
}
/// <summary>
/// Custom OPC UA <see cref="CustomNodeManager2"/> that owns the writable address space for
/// the OtOpcUa server. Variable nodes are declared by <see cref="EnsureVariable"/> (the applier's
@@ -48,15 +76,37 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
// re-implementing the interface is the only way to put an ACL decision on that path. Since #855 condition events no
// longer take it, and since #878 the decision there is a flat deny under enforcement (the SDK memoizes it, so it must
// not depend on grants). Every other member maps to the inherited implementation exactly as before.
public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IProjectedValueSink, IProjectedNamespacePageSink, IProjectedNodeLookup, IProjectedAnchorSink
{
/// <summary>Nonblocking lookup of the current projected parent readiness.</summary>
public Func<NodeId, ProjectedBrowseReadiness>? ProjectedBrowseReadiness { get; set; }
/// <summary>Caller-aware, nonblocking projected browse scheduler.</summary>
public IProjectedBrowseAccess? ProjectedBrowseAccess { get; set; }
/// <summary>Current caller-scoped projected data demand provider.</summary>
private IProjectedDataAccess? _projectedDataAccess;
public IProjectedDataAccess? ProjectedDataAccess
{
get => _projectedDataAccess;
set
{
_projectedDataAccess = value;
if (_authorizer is { } authorizer) authorizer.MappedNamespacePredicate = value is null ? null : IsProjectedDescendant;
}
}
private bool IsProjectedDescendant(NodeId nodeId) =>
(nodeId.NamespaceIndex == NamespaceIndexes[2] || nodeId.NamespaceIndex == NamespaceIndexes[3]) && (!_projectedAnchors.ContainsKey(nodeId) || _projectedRootLeaves.ContainsKey(nodeId));
/// <summary>Clock shared with the projected browse scheduler.</summary>
public TimeProvider ProjectedBrowseClock { get; set; } = TimeProvider.System;
/// <summary>v3 dual-namespace: both the Raw (device tree) and UNS (equipment tree) namespaces are
/// registered with the SDK so nodes can be minted in either. <see cref="V3NodeIds.RawNamespaceUri"/> is
/// registered FIRST (namespace index <see cref="NamespaceIndexes"/>[0]) and
/// <see cref="V3NodeIds.UnsNamespaceUri"/> SECOND ([1]); <see cref="NamespaceIndexForRealm"/> maps a realm
/// to its index. Which realm a node belongs to travels with each sink call as an
/// <see cref="AddressSpaceRealm"/> — the namespace is never parsed back out of the id string.</summary>
private static readonly string[] RegisteredNamespaceUris = { V3NodeIds.RawNamespaceUri, V3NodeIds.UnsNamespaceUri };
private static readonly string[] RegisteredNamespaceUris = { V3NodeIds.RawNamespaceUri, V3NodeIds.UnsNamespaceUri,
ProjectedDataIds.RawNamespaceUri, ProjectedDataIds.UnsNamespaceUri };
/// <summary>Transitional alias kept so the pre-v3 single-namespace integration tests
/// (<c>SubscriptionSurvivalTests</c>) still resolve a namespace index. It points at
@@ -176,13 +226,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
: this(server, configuration, logger)
{
_standby = standby ?? WarmStandbyState.Off;
if (_standby.WarmMode)
{
// Spec §4.6 item 1: ordinary-tag Value items are built by OrdinaryTagMonitoredItem, which marks each
// notification. Warm only — Unset/None keep the SDK's own manager.
m_monitoredItemManager.Dispose();
m_monitoredItemManager = new OrdinaryTagItemManager(this.ToAsyncNodeManager(), server);
}
// The wrapper retains the SDK's normal behavior for ordinary non-Warm items, and installs
// item-bound publication proofs for mapped data in every redundancy mode.
m_monitoredItemManager.Dispose();
m_monitoredItemManager = new OrdinaryTagItemManager(this.ToAsyncNodeManager(), server, this, _standby.WarmMode);
}
/// <summary>The Warm standby flags (Gitea #717). <see cref="WarmStandbyState.Off"/> unless the server is Warm.</summary>
@@ -225,7 +272,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
/// <param name="nodeId">The resolved SDK node id.</param>
/// <returns>The realm the node belongs to.</returns>
private AddressSpaceRealm RealmOf(NodeId nodeId) =>
nodeId.NamespaceIndex == NamespaceIndexes[0] ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns;
nodeId.NamespaceIndex == NamespaceIndexes[0] || nodeId.NamespaceIndex == NamespaceIndexes[2] ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns;
/// <summary>Zero-allocation realm-qualified map key. Replaces the formatted "ns=N;s=id" string key —
/// the (realm, id) pair is the same identity without the per-write NodeId + string allocations
@@ -703,7 +750,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
{
// #854 review: refuse new Server-object refreshes and let the ones in flight finish (the base's private
// NodeManagerOperation guard does this for its own paths).
_disposing = true;
lock (Lock) _disposing = true;
Interlocked.MemoryBarrier(); // the flag write must not be reordered after the in-flight read (#854 re-review)
if (!SpinWait.SpinUntil(() => Volatile.Read(ref _refreshesInFlight) == 0, TimeSpan.FromSeconds(10)))
_logger.LogWarning("Node manager disposed with {Count} Server-object ConditionRefresh call(s) still in flight after 10 s",
@@ -746,6 +793,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
{
value.UnsSubjectResolver = ResolveUnsAclSubject;
value.MappedSubjectResolver = _mappedSubjectResolver;
value.MappedNamespacePredicate = _projectedDataAccess is null ? null : IsProjectedDescendant;
}
_authorizer = value;
}
@@ -765,7 +813,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
}
}
private bool SecurityFilteringActive => AclEnforced || _mappedSubjectResolver is not null;
private bool SecurityFilteringActive => AclEnforced || _mappedSubjectResolver is not null || NamespaceIndexes.Count >= 4;
/// <summary>
/// True when a wired authorizer is switched on — i.e. when ACL grants, rather than the server-wide
@@ -4135,6 +4183,640 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
}
}
private readonly ConcurrentDictionary<NodeId, (ProjectedAnchorDefinition Definition, BaseInstanceState Node)> _projectedAnchors = new();
private readonly ConcurrentDictionary<NodeId, byte> _projectedRootLeaves = new();
/// <summary>Installs an anchor only beneath its exact live local parent, without remote authority.</summary>
public bool TryEnsureProjectedAnchor(ProjectedAnchorDefinition definition, out NodeId? nodeId)
{
nodeId = null;
if (definition is null || definition.Realm is not (DataRealm.Raw or DataRealm.Uns) ||
string.IsNullOrWhiteSpace(definition.LocalIdentifier) || string.IsNullOrWhiteSpace(definition.BrowseName) ||
string.IsNullOrWhiteSpace(definition.MappingId) || string.IsNullOrWhiteSpace(definition.LocalSubject) ||
!ProjectedDataIds.TryDecodeIdentifier(definition.LocalIdentifier, out var mappingId, out _) || mappingId != definition.MappingId ||
definition.MappingRevision <= 0 || !definition.Lifetime.IsActive || definition.AuthorityIsCurrent is null)
return false;
lock (Lock)
{
if (_disposing || !definition.AuthorityIsCurrent() ||
GetManagerHandle(definition.Parent) is not NodeHandle { Node: FolderState parent } || parent.NodeId != definition.Parent)
return false;
var id = new NodeId(definition.LocalIdentifier, definition.Realm == DataRealm.Raw ? NamespaceIndexes[2] : NamespaceIndexes[3]);
if (_projectedAnchors.TryGetValue(id, out var old))
{
if (old.Definition.Parent != definition.Parent || old.Definition.MappingId != definition.MappingId ||
old.Definition.MappingRevision != definition.MappingRevision || old.Definition.LocalSubject != definition.LocalSubject ||
!old.Definition.AuthorityIsCurrent()) return false;
nodeId = id; return true;
}
if (GetManagerHandle(id) is not null) return false;
var charge = ProjectedAnchorCharge(definition);
if (!ReserveProjectedNode(charge)) return false;
var folder = new FolderState(parent)
{
NodeId = id, BrowseName = new QualifiedName(definition.LocalIdentifier, id.NamespaceIndex),
DisplayName = new LocalizedText(definition.BrowseName), EventNotifier = EventNotifiers.None,
TypeDefinitionId = ObjectTypeIds.FolderType, ReferenceTypeId = ReferenceTypeIds.Organizes
};
if (!definition.AuthorityIsCurrent()) return false;
parent.AddChild(folder); AddPredefinedNode(SystemContext, folder);
_projectedAnchors[id] = (definition, folder);
_projectedNodeCharges.Add(id, charge); _projectedNodeBytes += charge;
nodeId = id; return true;
}
}
private static long ProjectedAnchorCharge(ProjectedAnchorDefinition definition) =>
checked(1024L + 2L * (definition.LocalIdentifier.Length + definition.BrowseName.Length + definition.LocalSubject.Length + definition.MappingId.Length));
/// <inheritdoc />
public bool TryRemoveProjectedAnchor(NodeId nodeId, ProjectedAnchorDefinition expected)
{
lock (Lock)
{
if (_disposing || !_projectedAnchors.TryGetValue(nodeId, out var anchor) ||
!ReferenceEquals(anchor.Definition, expected)) return false;
var mappingId = anchor.Definition.MappingId;
foreach (var id in _projectedVariables.Keys.Where(id =>
ProjectedDataIds.TryDecodeIdentifier(id.IdentifierAsString, out var mapping, out _) && mapping == mappingId).ToArray())
{
if (_projectedVariables.Remove(id, out var child))
{
if (_projectedDefinitions.Remove(id, out var definition)) RetireProjectedCharge(id, definition.Lifetime);
RemoveProjectedSample(id);
TombstoneMonitoredNode(id, UtcNow);
child.Node.Parent?.RemoveChild(child.Node); PredefinedNodes?.Remove(id);
}
}
_projectedAnchors.TryRemove(nodeId, out _);
_projectedRootLeaves.TryRemove(nodeId, out _);
RetireProjectedCharge(nodeId, anchor.Definition.Lifetime);
anchor.Node.Parent?.RemoveChild(anchor.Node); PredefinedNodes?.Remove(nodeId);
return true;
}
}
/// <inheritdoc />
public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId)
{
nodeId = null;
if (string.IsNullOrEmpty(identifier)) return false;
lock (Lock)
{
if (_disposing) return false;
var index = Array.IndexOf(RegisteredNamespaceUris, namespaceUri);
if (index < 0) return false;
nodeId = new NodeId(identifier, NamespaceIndexes[index]);
return true;
}
}
/// <inheritdoc />
public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition)
{
lock (Lock)
{
if (!_disposing && _projectedDefinitions.TryGetValue(nodeId, out definition) && definition.Lifetime.IsActive && definition.AuthorityIsCurrent()) return true;
definition = null; return false;
}
}
private int _maxProjectedNodes = 4096;
private long _maxProjectedNodeBytes = 16 * 1024 * 1024;
private long _projectedNodeBytes;
private readonly Dictionary<NodeId, long> _projectedNodeCharges = new();
/// <summary>Configures bounded retained projected nodes before any are installed.</summary>
public void ConfigureProjectedNodeLimits(int maxNodes, long maxBytes)
{
if (maxNodes <= 0 || maxBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxNodes));
lock (Lock)
{
if (_projectedVariables.Count != 0 || !_projectedAnchors.IsEmpty) throw new InvalidOperationException("Projected nodes are already active.");
_maxProjectedNodes = maxNodes; _maxProjectedNodeBytes = maxBytes;
}
}
private static long ProjectedNodeCharge(ProjectedVariableDefinition definition)
{
var authorityBytes = (definition.AuthorityIsCurrent.Target as IProjectedRetainedAuthority)?.RetainedBytes ?? 0;
if (authorityBytes < 0) throw new ArgumentOutOfRangeException(nameof(definition));
var metadata = definition.Metadata;
return checked(1024L + authorityBytes + 2L * (definition.LocalIdentifier.Length + metadata.BrowseName.Length +
metadata.NodeKind.Length + metadata.View.Subject.Length + metadata.View.Address.Identifier.Length +
metadata.View.Address.NamespaceUri.Length + metadata.View.Address.OriginClusterId.Length + metadata.View.Address.IdentifierKind.Length +
(metadata.View.MappingId?.Length ?? 0) + (metadata.StableSourceId?.Length ?? 0) + (metadata.EngineeringUnits?.Length ?? 0)) +
4L * metadata.Dimensions.Count);
}
private int _retiredProjectedNodes;
private long _retiredProjectedBytes;
private void RetireProjectedCharge(NodeId id, ProjectedNodeLifetime lifetime)
{
if (!_projectedNodeCharges.Remove(id, out var charge)) { lifetime.ForceRetire(); return; }
_projectedNodeBytes -= charge;
Interlocked.Add(ref _retiredProjectedBytes, charge);
Interlocked.Increment(ref _retiredProjectedNodes);
lifetime.ForceRetire(() =>
{
Interlocked.Add(ref _retiredProjectedBytes, -charge);
Interlocked.Decrement(ref _retiredProjectedNodes);
});
}
private bool ReserveProjectedNode(long bytes)
{
if (bytes <= 0 || bytes > _maxProjectedNodeBytes) return false;
if (_projectedVariables.Count + _projectedAnchors.Count - _projectedRootLeaves.Count + Volatile.Read(ref _retiredProjectedNodes) < _maxProjectedNodes && bytes <= _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) return true;
foreach (var pair in _projectedDefinitions.ToArray())
{
if (_projectedRootLeaves.ContainsKey(pair.Key) || pair.Value.AuthorityIsCurrent() ||
_projectedVariables.Values.Any(child => child.Parent == pair.Key) || !pair.Value.Lifetime.TryRetire()) continue;
if (!_projectedVariables.Remove(pair.Key, out var entry)) continue;
_projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key);
if (_projectedNodeCharges.Remove(pair.Key, out var oldBytes)) _projectedNodeBytes -= oldBytes;
entry.Node.Parent?.RemoveChild(entry.Node); PredefinedNodes?.Remove(pair.Key);
if (_projectedVariables.Count + _projectedAnchors.Count - _projectedRootLeaves.Count + Volatile.Read(ref _retiredProjectedNodes) < _maxProjectedNodes && bytes <= _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) return true;
}
foreach (var pair in _projectedAnchors.ToArray())
{
if (pair.Value.Definition.AuthorityIsCurrent() ||
_projectedVariables.Values.Any(node => node.Parent == pair.Key) || !pair.Value.Definition.Lifetime.TryRetire()) continue;
if (!_projectedAnchors.TryRemove(pair.Key, out var anchor)) continue;
if (_projectedRootLeaves.TryRemove(pair.Key, out _))
{ _projectedVariables.Remove(pair.Key); _projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key); }
if (_projectedNodeCharges.Remove(pair.Key, out var oldBytes)) _projectedNodeBytes -= oldBytes;
anchor.Node.Parent?.RemoveChild(anchor.Node); PredefinedNodes?.Remove(pair.Key);
if (_projectedVariables.Count + _projectedAnchors.Count - _projectedRootLeaves.Count + Volatile.Read(ref _retiredProjectedNodes) < _maxProjectedNodes && bytes <= _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) return true;
}
return false;
}
private readonly Dictionary<NodeId, ProjectedVariableDefinition> _projectedDefinitions = new();
private readonly ProjectedCandidateBudget _projectedCandidateBudget = new(65_536, 16 * 1024 * 1024);
internal ProjectedCandidateBudget ProjectedCandidateBudget => _projectedCandidateBudget;
internal bool IsProjectedItem(NodeId nodeId) => IsProjectedDescendant(nodeId);
internal bool CanDispatchProjectedWrite()
{
try { return !_disposing && !_standby.RefusesMutations && (NativeAlarmAckPrimaryGate?.Invoke() ?? true); }
catch (Exception) { return false; }
}
internal bool IsProjectedBrowseNode(NodeId nodeId) =>
nodeId.NamespaceIndex == NamespaceIndexes[2] || nodeId.NamespaceIndex == NamespaceIndexes[3];
internal bool CanBrowseProjectedParent(NodeId nodeId, RoleCarryingUserIdentity caller)
{
if (_projectedAnchors.ContainsKey(nodeId)) return Permits(caller, OpcUaOperation.Browse, nodeId);
var access = ProjectedDataAccess;
IProjectedDemandLease? demand = null;
try { return access is not null && access.TryAcquire(nodeId, caller, DataOperations.Browse, out demand) && demand is { IsValid: true }; }
catch (Exception) { return false; }
finally { demand?.Dispose(); }
}
internal ServiceResult? ValidateProjectedView(OperationContext context, ViewDescription? view)
{
if (view is null || ViewDescription.IsDefault(view)) return null;
try { ValidateViewDescription(SystemContext.Copy(context), view); return null; }
catch (ServiceResultException ex) { return ex.StatusCode; }
}
internal bool TryDescribeProjectedParent(NodeId nodeId, RoleCarryingUserIdentity caller, out ReferenceDescription? reference)
{
reference = null;
NodeId parent;
lock (Lock)
{
if (_projectedAnchors.TryGetValue(nodeId, out var anchor)) parent = anchor.Definition.Parent;
else if (_projectedVariables.TryGetValue(nodeId, out var entry)) parent = entry.Parent;
else return false;
}
if (IsProjectedBrowseNode(parent))
{
if (!CanBrowseProjectedParent(parent, caller)) return false;
}
else if (!Permits(caller, OpcUaOperation.Browse, parent)) return false;
lock (Lock)
{
if (_disposing || GetManagerHandle(parent) is not NodeHandle { Node: BaseInstanceState node }) return false;
reference = new ReferenceDescription { NodeId = new ExpandedNodeId(parent), BrowseName = node.BrowseName,
DisplayName = node.DisplayName, NodeClass = node.NodeClass, ReferenceTypeId = ReferenceTypeIds.Organizes,
IsForward = false, TypeDefinition = new ExpandedNodeId(node.TypeDefinitionId) };
return true;
}
}
internal bool TryDescribeProjectedChild(NodeId nodeId, RoleCarryingUserIdentity caller, out ReferenceDescription? reference)
{
reference = null;
var access = ProjectedDataAccess;
IProjectedDemandLease? demand = null;
try
{
if (access is null || !access.TryAcquire(nodeId, caller, DataOperations.Browse, out demand) || demand is null || !demand.IsValid) return false;
lock (Lock)
{
if (_disposing || !_projectedVariables.TryGetValue(nodeId, out var entry) || !entry.Guard() || !demand.IsValid) return false;
reference = new ReferenceDescription
{
NodeId = new ExpandedNodeId(nodeId), BrowseName = entry.Node.BrowseName, DisplayName = entry.Node.DisplayName,
NodeClass = entry.Node.NodeClass, ReferenceTypeId = ReferenceTypeIds.Organizes, IsForward = true,
TypeDefinition = new ExpandedNodeId(entry.Node.TypeDefinitionId)
};
}
return demand.IsValid;
}
catch (Exception) { reference = null; return false; }
finally { demand?.Dispose(); }
}
internal bool RequestProjectedSnapshot(IProjectedDemandLease demand) => ProjectedDataAccess?.RequestFreshSnapshot(demand) == true;
internal void ObserveCurrentProjectedSource(ProjectedMonitoredItem item)
{
lock (Lock)
if (_projectedSamples.TryGetValue(item.ProjectedNodeId, out var sample)) item.ObserveSample(sample);
}
internal bool IsProjectedDefinitionCurrent(NodeId nodeId, ProjectedVariableDefinition definition)
{
lock (Lock) return !_disposing && _projectedDefinitions.TryGetValue(nodeId, out var current) &&
ReferenceEquals(current.Lifetime, definition.Lifetime) && current.Lifetime.IsActive && current.AuthorityIsCurrent();
}
internal bool TryAcquireProjectedItem(ServerSystemContext context, NodeId nodeId, double publishingInterval,
out IProjectedDemandLease? demand, out ProjectedValueWrite? sample, out ProjectedVariableDefinition? definition)
{
demand = null; sample = null; definition = null;
var identity = IdentityOf(context);
var access = ProjectedDataAccess;
var accepted = false;
try
{
if (identity is null || access is null || !TryResolve(nodeId, out definition) || definition is null ||
!access.TryAcquire(nodeId, identity, DataOperations.Subscribe, out demand) || demand is null || !demand.IsValid ||
!access.StartSubscription(demand, TimeSpan.FromMilliseconds(Math.Max(0, publishingInterval)))) return false;
lock (Lock) _projectedSamples.TryGetValue(nodeId, out sample);
if (!demand.IsValid || !IsProjectedDefinitionCurrent(nodeId, definition)) return false;
accepted = true;
return true;
}
finally
{
if (!accepted) { demand?.Dispose(); demand = null; }
}
}
private readonly Dictionary<NodeId, ProjectedValueWrite> _projectedSamples = new();
private readonly Dictionary<NodeId, long> _projectedSampleCharges = new();
private long _projectedSampleBytes;
private void RemoveProjectedSample(NodeId id)
{
_projectedSamples.Remove(id);
if (_projectedSampleCharges.Remove(id, out var bytes)) _projectedSampleBytes -= bytes;
}
private static long EstimateProjectedSample(object? value)
{
checked
{
long bytes = 256;
if (value is string text) bytes += 2L * text.Length;
else if (value is Array array)
{
if (array.Rank != 1 || array.Length > 65_536) throw new ArgumentException("Unsupported projected array.");
bytes += 64L * array.Length;
if (array is string[] strings) foreach (var item in strings) bytes += 2L * (item?.Length ?? 0);
}
return bytes;
}
}
bool IProjectedValueSink.TryPublish(IReadOnlyList<ProjectedValueWrite> values)
{
ArgumentNullException.ThrowIfNull(values);
if (values.Count == 0) return false;
var valid = true;
long sampleDelta = 0;
var snapshotRequests = new List<ProjectedMonitoredItem>();
lock (Lock)
{
if (_disposing) return false;
var targets = new List<(NodeId Id, BaseDataVariableState Node, ProjectedValueWrite Value, DataMetadata Metadata, long Charge)>(values.Count);
var seen = new HashSet<NodeId>();
foreach (var value in values)
{
if (value is null || value.Proof is null || value.Realm is not (DataRealm.Raw or DataRealm.Uns)) { valid = false; continue; }
var id = new NodeId(value.LocalIdentifier, value.Realm == DataRealm.Raw ? NamespaceIndexes[2] : NamespaceIndexes[3]);
if (!seen.Add(id) || !_projectedVariables.TryGetValue(id, out var target) || target.Generation != value.ProjectionGeneration ||
!value.Proof.IsValid || !target.Guard() || target.Node is not BaseDataVariableState || value.Serving.ServingGeneration <= 0 ||
(target.Metadata.Serving is { } expected && expected != value.Serving) || !ProjectedValueMatches(target.Metadata, value.Snapshot.Value))
{ valid = false; continue; }
try
{
value.OriginAgeBounds.Advance(value.Proof.Clock.GetElapsedTime(value.ReceivedTimestamp, value.Proof.Clock.GetTimestamp()));
}
catch (Exception ex) when (ex is ArgumentException or OverflowException) { valid = false; continue; }
try
{
var charge = EstimateProjectedSample(value.Snapshot.Value);
sampleDelta = checked(sampleDelta + charge - _projectedSampleCharges.GetValueOrDefault(id));
targets.Add((id, (BaseDataVariableState)target.Node, value, target.Metadata, charge));
}
catch (Exception ex) when (ex is ArgumentException or OverflowException) { valid = false; }
}
if (sampleDelta > _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) valid = false;
if (valid && targets.Any(target => !target.Value.Proof.IsValid)) valid = false;
if (!valid || targets.Count != values.Count)
{
// Retire only matching generations: a late old owner cannot invalidate a new projection.
foreach (var value in values)
{
if (value is null || value.Realm is not (DataRealm.Raw or DataRealm.Uns)) continue;
var id = new NodeId(value.LocalIdentifier, value.Realm == DataRealm.Raw ? NamespaceIndexes[2] : NamespaceIndexes[3]);
if (_projectedVariables.TryGetValue(id, out var target) && target.Generation == value.ProjectionGeneration && target.Node is BaseDataVariableState variable)
{
RemoveProjectedSample(id);
variable.Value = Variant.Null;
variable.StatusCode = StatusCodes.BadWaitingForInitialData;
variable.ClearChangeMasks(SystemContext, false);
}
}
}
else
{
foreach (var target in targets)
{
var source = target.Value.Snapshot.Value;
var detached = target.Value with { Snapshot = target.Value.Snapshot with { Value = source is Array array ? array.Clone() : source } };
foreach (var item in _liveItems.Keys.OfType<ProjectedMonitoredItem>())
if (item.ProjectedNodeId == target.Id && item.ObserveSample(detached)) snapshotRequests.Add(item);
target.Node.Value = SdkValueBoundary.FromClr(detached.Snapshot.Value,
target.Metadata.ValueKind == DataValueKind.Array && target.Metadata.ArrayElementKind == DataValueKind.UInt8);
target.Node.StatusCode = detached.Snapshot.StatusCode;
target.Node.Timestamp = detached.Snapshot.SourceTimestampUtc ?? DateTime.MinValue;
RemoveProjectedSample(target.Id);
_projectedSamples[target.Id] = detached; _projectedSampleCharges[target.Id] = target.Charge; _projectedSampleBytes += target.Charge;
target.Node.ClearChangeMasks(SystemContext, false);
}
}
}
if (!valid) foreach (var value in values) value?.Proof?.Invalidate();
foreach (var item in snapshotRequests.Distinct()) item.RequestBaseline();
return valid;
}
private static bool ProjectedValueMatches(DataMetadata metadata, object? value)
{
if (value is null) return true;
var kind = metadata.ValueKind;
if (kind == DataValueKind.Array)
{
if (value is not Array array || array.Rank != 1 || metadata.ValueRank != 1 || metadata.Dimensions.Count != 1 ||
(metadata.Dimensions[0] != 0 && array.Length != metadata.Dimensions[0])) return false;
kind = metadata.ArrayElementKind ?? DataValueKind.Unspecified;
var elementType = array.GetType().GetElementType();
var expectedType = kind switch
{
DataValueKind.Boolean => typeof(bool), DataValueKind.Int8 => typeof(sbyte), DataValueKind.UInt8 => typeof(byte),
DataValueKind.Int16 => typeof(short), DataValueKind.UInt16 => typeof(ushort), DataValueKind.Int32 => typeof(int),
DataValueKind.UInt32 => typeof(uint), DataValueKind.Int64 => typeof(long), DataValueKind.UInt64 => typeof(ulong),
DataValueKind.Float => typeof(float), DataValueKind.Double => typeof(double), DataValueKind.String => typeof(string),
DataValueKind.Timestamp => typeof(DateTime), _ => null
};
if (elementType != expectedType) return false;
foreach (var element in array) if (!ProjectedScalarMatches(kind, element)) return false;
return true;
}
return ProjectedScalarMatches(kind, value);
}
private static bool ProjectedScalarMatches(DataValueKind kind, object? value) => value is not null && kind switch
{
DataValueKind.Boolean => value is bool, DataValueKind.Int8 => value is sbyte, DataValueKind.UInt8 => value is byte,
DataValueKind.Int16 => value is short, DataValueKind.UInt16 => value is ushort, DataValueKind.Int32 => value is int,
DataValueKind.UInt32 => value is uint, DataValueKind.Int64 => value is long, DataValueKind.UInt64 => value is ulong,
DataValueKind.Float => value is float, DataValueKind.Double => value is double, DataValueKind.String => value is string,
DataValueKind.Timestamp => value is DateTime or DateTimeOffset, _ => false
};
private readonly Dictionary<NodeId, (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func<bool> Guard)> _projectedVariables = new();
bool IProjectedNamespacePageSink.TryApply(NodeId parent, IReadOnlyList<ProjectedVariableDefinition> nodes, Func<bool> commit)
{
ArgumentNullException.ThrowIfNull(nodes);
ArgumentNullException.ThrowIfNull(commit);
if (nodes.Count > 4096) return false;
lock (Lock)
{
if (_disposing) return false;
var added = new List<NodeId>();
var renewals = new List<(NodeId Id, ProjectedVariableDefinition Definition, long Charge)>();
var seen = new HashSet<NodeId>();
var applied = false;
try
{
foreach (var definition in nodes)
{
if (definition is null || definition.Parent != parent || definition.Realm is not (DataRealm.Raw or DataRealm.Uns)) return false;
var id = new NodeId(definition.LocalIdentifier, definition.Realm == DataRealm.Raw ? NamespaceIndexes[2] : NamespaceIndexes[3]);
if (!seen.Add(id)) return false;
if (_projectedVariables.TryGetValue(id, out var existing))
{
if (!_projectedDefinitions.TryGetValue(id, out var old) || existing.Parent != parent ||
existing.Generation != definition.ProjectionGeneration || !definition.AuthorityIsCurrent() ||
old.Metadata.View != definition.Metadata.View || old.Metadata.BrowseName != definition.Metadata.BrowseName ||
old.Metadata.NodeKind != definition.Metadata.NodeKind || old.Metadata.ValueKind != definition.Metadata.ValueKind ||
old.Metadata.ValueRank != definition.Metadata.ValueRank || old.Metadata.ArrayElementKind != definition.Metadata.ArrayElementKind ||
!old.Metadata.Dimensions.SequenceEqual(definition.Metadata.Dimensions)) return false;
var renewed = ReferenceEquals(definition.Lifetime, old.Lifetime) ? definition : definition with { Lifetime = old.Lifetime };
renewals.Add((id, renewed, checked(ProjectedNodeCharge(renewed) +
(_projectedRootLeaves.ContainsKey(id) ? ProjectedAnchorCharge(_projectedAnchors[id].Definition) : 0))));
continue;
}
if (!TryEnsureProjectedVariable(definition, out var created) || created != id) return false;
added.Add(id);
}
long renewalDelta = 0;
foreach (var renewal in renewals) renewalDelta = checked(renewalDelta + renewal.Charge - _projectedNodeCharges[renewal.Id]);
if (renewalDelta > _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes ||
nodes.Any(node => !node.AuthorityIsCurrent()) || !commit() || nodes.Any(node => !node.AuthorityIsCurrent())) return false;
foreach (var renewal in renewals)
{
var previous = _projectedVariables[renewal.Id];
_projectedVariables[renewal.Id] = (previous.Parent, previous.Generation, renewal.Definition.Metadata,
previous.Node, renewal.Definition.AuthorityIsCurrent);
_projectedDefinitions[renewal.Id] = renewal.Definition;
_projectedNodeBytes += renewal.Charge - _projectedNodeCharges[renewal.Id];
_projectedNodeCharges[renewal.Id] = renewal.Charge;
}
applied = true;
return true;
}
finally
{
if (!applied)
foreach (var id in added)
{
if (!_projectedVariables.Remove(id, out var entry)) continue;
RemoveProjectedSample(id);
_projectedDefinitions.Remove(id);
if (_projectedNodeCharges.Remove(id, out var charge)) _projectedNodeBytes -= charge;
entry.Node.Parent?.RemoveChild(entry.Node);
PredefinedNodes?.Remove(id);
}
}
}
}
bool IProjectedNamespacePageSink.TryApplyRootLeaf(NodeId anchorId, ProjectedVariableDefinition rootDefinition, Func<bool> commit)
{
ArgumentNullException.ThrowIfNull(rootDefinition); ArgumentNullException.ThrowIfNull(commit);
lock (Lock)
{
if (_disposing || !_projectedAnchors.TryGetValue(anchorId, out var anchor) ||
(rootDefinition.Parent != anchor.Definition.Parent && rootDefinition.Parent != anchorId) || rootDefinition.LocalIdentifier != anchor.Definition.LocalIdentifier ||
rootDefinition.Realm != anchor.Definition.Realm || rootDefinition.ProjectionGeneration <= 0 ||
!ProjectedDataIds.TryDecodeIdentifier(rootDefinition.LocalIdentifier, out var mapping, out var origin) ||
mapping != anchor.Definition.MappingId || rootDefinition.Metadata.View.MappingId != mapping ||
rootDefinition.Metadata.View.Address != origin || rootDefinition.Metadata.View.Realm != rootDefinition.Realm ||
rootDefinition.Metadata.NodeKind is not ("Variable" or "Tag") ||
!anchor.Definition.AuthorityIsCurrent() || !rootDefinition.AuthorityIsCurrent() ||
!_projectedNodeCharges.TryGetValue(anchorId, out var anchorCharge) ||
GetManagerHandle(anchor.Definition.Parent) is not NodeHandle { Node: FolderState parent }) return false;
var installed = rootDefinition with { Parent = anchor.Definition.Parent, Lifetime = anchor.Definition.Lifetime };
if (anchor.Node is BaseDataVariableState existingNode)
{
if (!_projectedRootLeaves.ContainsKey(anchorId) || !_projectedDefinitions.TryGetValue(anchorId, out var old) ||
!_projectedVariables.TryGetValue(anchorId, out var existing) || existing.Generation != installed.ProjectionGeneration ||
old.Metadata.View != installed.Metadata.View || old.Metadata.BrowseName != installed.Metadata.BrowseName ||
old.Metadata.NodeKind != installed.Metadata.NodeKind || old.Metadata.ValueKind != installed.Metadata.ValueKind ||
old.Metadata.ValueRank != installed.Metadata.ValueRank || old.Metadata.ArrayElementKind != installed.Metadata.ArrayElementKind ||
!old.Metadata.Dimensions.SequenceEqual(installed.Metadata.Dimensions)) return false;
var renewedCharge = checked(ProjectedAnchorCharge(anchor.Definition) + ProjectedNodeCharge(installed));
var delta = renewedCharge - anchorCharge;
if (delta > _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes ||
!installed.AuthorityIsCurrent() || !commit() || !installed.AuthorityIsCurrent()) return false;
_projectedVariables[anchorId] = (existing.Parent, existing.Generation, installed.Metadata, existingNode, installed.AuthorityIsCurrent);
_projectedDefinitions[anchorId] = installed;
_projectedNodeCharges[anchorId] = renewedCharge;
_projectedNodeBytes += delta;
return true;
}
if (anchor.Node is not FolderState folder) return false;
var children = new List<BaseInstanceState>(); folder.GetChildren(SystemContext, children);
if (children.Count != 0) return false;
var isArray = rootDefinition.Metadata.ValueKind == DataValueKind.Array;
if (isArray ? rootDefinition.Metadata.ValueRank != 1 || rootDefinition.Metadata.Dimensions.Count != 1 || rootDefinition.Metadata.Dimensions[0] < 0 :
rootDefinition.Metadata.ValueRank != -1 || rootDefinition.Metadata.Dimensions.Count != 0) return false;
var kind = isArray ? rootDefinition.Metadata.ArrayElementKind ?? DataValueKind.Unspecified : rootDefinition.Metadata.ValueKind;
var typeName = kind switch
{
DataValueKind.Boolean => "Boolean", DataValueKind.Int8 => "SByte", DataValueKind.UInt8 => "Byte",
DataValueKind.Int16 => "Int16", DataValueKind.UInt16 => "UInt16", DataValueKind.Int32 => "Int32",
DataValueKind.UInt32 => "UInt32", DataValueKind.Int64 => "Int64", DataValueKind.UInt64 => "UInt64",
DataValueKind.Float => "Float", DataValueKind.Double => "Double", DataValueKind.String => "String",
DataValueKind.Timestamp => "DateTime", _ => null
};
if (typeName is null) return false;
var charge = ProjectedNodeCharge(rootDefinition);
if (charge > _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) return false;
var variable = new BaseDataVariableState(parent)
{
NodeId = anchorId, BrowseName = new QualifiedName(anchor.Definition.BrowseName, anchorId.NamespaceIndex),
DisplayName = new LocalizedText(anchor.Definition.BrowseName), TypeDefinitionId = VariableTypeIds.BaseDataVariableType,
ReferenceTypeId = ReferenceTypeIds.Organizes, DataType = ResolveBuiltInDataType(typeName),
ValueRank = isArray ? ValueRanks.OneDimension : ValueRanks.Scalar,
ArrayDimensions = isArray ? (ArrayOf<uint>)[checked((uint)rootDefinition.Metadata.Dimensions[0])] : default,
AccessLevel = AccessLevels.CurrentRead, UserAccessLevel = AccessLevels.CurrentRead,
Value = Variant.Null, StatusCode = StatusCodes.BadWaitingForInitialData, Timestamp = DateTime.MinValue
};
var accepted = false;
var charged = false;
try
{
parent.RemoveChild(folder); PredefinedNodes?.Remove(anchorId);
parent.AddChild(variable); AddPredefinedNode(SystemContext, variable);
_projectedAnchors[anchorId] = (anchor.Definition, variable);
_projectedRootLeaves[anchorId] = 0;
_projectedVariables.Add(anchorId, (anchor.Definition.Parent, installed.ProjectionGeneration, installed.Metadata, variable, installed.AuthorityIsCurrent));
_projectedDefinitions.Add(anchorId, installed);
_projectedNodeCharges[anchorId] = anchorCharge + charge; _projectedNodeBytes += charge; charged = true;
if (!installed.AuthorityIsCurrent() || !commit() || !installed.AuthorityIsCurrent()) return false;
accepted = true; return true;
}
finally
{
if (!accepted)
{
_projectedVariables.Remove(anchorId); _projectedDefinitions.Remove(anchorId); _projectedRootLeaves.TryRemove(anchorId, out _);
_projectedNodeCharges[anchorId] = anchorCharge;
if (charged) _projectedNodeBytes -= charge;
variable.Parent?.RemoveChild(variable); PredefinedNodes?.Remove(anchorId);
parent.AddChild(folder); AddPredefinedNode(SystemContext, folder); _projectedAnchors[anchorId] = anchor;
}
}
}
}
bool IProjectedNamespacePageSink.TryRemove(NodeId nodeId, ProjectedVariableDefinition expected)
{
lock (Lock)
{
if (_disposing || _projectedRootLeaves.ContainsKey(nodeId) || !_projectedDefinitions.TryGetValue(nodeId, out var current) || !ReferenceEquals(current, expected) ||
_projectedVariables.Values.Any(child => child.Parent == nodeId) || !_projectedVariables.Remove(nodeId, out var entry)) return false;
_projectedDefinitions.Remove(nodeId); RemoveProjectedSample(nodeId); RetireProjectedCharge(nodeId, current.Lifetime);
TombstoneMonitoredNode(nodeId, UtcNow);
entry.Node.Parent?.RemoveChild(entry.Node); PredefinedNodes?.Remove(nodeId);
return true;
}
}
/// <summary>Materializes one checked scalar under its exact existing parent. Access stays denied until its live proof is wired.</summary>
internal bool TryEnsureProjectedVariable(ProjectedVariableDefinition definition, out NodeId? nodeId)
{
nodeId = null;
if (definition is null || definition.Metadata is null || definition.AuthorityIsCurrent is null ||
definition.ProjectionGeneration <= 0 || !definition.Lifetime.IsActive ||
!ProjectedDataIds.TryDecodeIdentifier(definition.LocalIdentifier, out var mapping, out var origin) ||
definition.Metadata.View.MappingId != mapping || definition.Metadata.View.Address != origin ||
definition.Metadata.View.Realm != definition.Realm) return false;
var isFolder = definition.Metadata.NodeKind == "Folder";
var isArray = definition.Metadata.ValueKind == DataValueKind.Array;
if (isFolder && (definition.Metadata.ValueKind != DataValueKind.Null || definition.Metadata.ValueRank != -1 || definition.Metadata.Dimensions.Count != 0)) return false;
if (!isFolder && definition.Metadata.NodeKind is not ("Variable" or "Tag")) return false;
if (!isFolder && (isArray ? definition.Metadata.ValueRank != 1 || definition.Metadata.Dimensions.Count != 1 || definition.Metadata.Dimensions[0] < 0 :
definition.Metadata.ValueRank != -1 || definition.Metadata.Dimensions.Count != 0)) return false;
var valueKind = isArray ? definition.Metadata.ArrayElementKind ?? DataValueKind.Unspecified : definition.Metadata.ValueKind;
var typeName = valueKind switch
{
DataValueKind.Boolean => "Boolean", DataValueKind.Int8 => "SByte", DataValueKind.UInt8 => "Byte",
DataValueKind.Int16 => "Int16", DataValueKind.UInt16 => "UInt16", DataValueKind.Int32 => "Int32",
DataValueKind.UInt32 => "UInt32", DataValueKind.Int64 => "Int64", DataValueKind.UInt64 => "UInt64",
DataValueKind.Float => "Float", DataValueKind.Double => "Double", DataValueKind.String => "String",
DataValueKind.Timestamp => "DateTime", _ => null
};
if ((!isFolder && typeName is null) || definition.Realm is not (DataRealm.Raw or DataRealm.Uns)) return false;
lock (Lock)
{
if (_disposing || !definition.AuthorityIsCurrent()) return false;
if (GetManagerHandle(definition.Parent) is not NodeHandle { Node: FolderState parent } || parent.NodeId != definition.Parent) return false;
var index = definition.Realm == DataRealm.Raw ? NamespaceIndexes[2] : NamespaceIndexes[3];
var candidate = new NodeId(definition.LocalIdentifier, index);
if (_projectedVariables.TryGetValue(candidate, out var existing))
{
if (existing.Parent != definition.Parent || existing.Generation != definition.ProjectionGeneration || existing.Metadata != definition.Metadata) return false;
nodeId = candidate; return true;
}
if (GetManagerHandle(candidate) is not null) return false;
var charge = ProjectedNodeCharge(definition);
if (!ReserveProjectedNode(charge)) return false;
BaseInstanceState node = isFolder
? new FolderState(parent) { NodeId = candidate, BrowseName = new QualifiedName(definition.Metadata.BrowseName, index),
DisplayName = new LocalizedText(definition.Metadata.BrowseName), TypeDefinitionId = ObjectTypeIds.FolderType,
ReferenceTypeId = ReferenceTypeIds.Organizes, EventNotifier = EventNotifiers.None }
: new BaseDataVariableState(parent) { NodeId = candidate, BrowseName = new QualifiedName(definition.Metadata.BrowseName, index),
DisplayName = new LocalizedText(definition.Metadata.BrowseName), TypeDefinitionId = VariableTypeIds.BaseDataVariableType,
ReferenceTypeId = ReferenceTypeIds.Organizes, DataType = ResolveBuiltInDataType(typeName!),
ValueRank = isArray ? ValueRanks.OneDimension : ValueRanks.Scalar,
ArrayDimensions = isArray ? (ArrayOf<uint>)[checked((uint)definition.Metadata.Dimensions[0])] : default,
AccessLevel = AccessLevels.CurrentRead, UserAccessLevel = AccessLevels.CurrentRead,
Value = Variant.Null, StatusCode = StatusCodes.BadWaitingForInitialData, Timestamp = DateTime.MinValue };
if (!definition.AuthorityIsCurrent()) return false;
parent.AddChild(node); AddPredefinedNode(SystemContext, node);
_projectedVariables.Add(candidate, (definition.Parent, definition.ProjectionGeneration, definition.Metadata, node, definition.AuthorityIsCurrent));
_projectedDefinitions.Add(candidate, definition);
_projectedNodeCharges.Add(candidate, charge); _projectedNodeBytes += charge;
nodeId = candidate; return true;
}
}
/// <summary>Records <paramref name="child"/> under <paramref name="parent"/> in the P2 subtree index. MUST be
/// called under <c>Lock</c>. Idempotent for the same pair; a child re-indexed under another parent moves.</summary>
private void IndexChild(RealmKey parent, RealmKey child)
@@ -4738,8 +5420,17 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
/// EnsureFolder + WriteValue on the next pass.</summary>
public void RebuildAddressSpace()
{
IProjectedSamplePublicationProof[] retiredProofs;
lock (Lock)
{
retiredProofs = _projectedSamples.Values.Select(sample => sample.Proof).Distinct().ToArray();
foreach (var item in _liveItems.Keys.OfType<ProjectedMonitoredItem>()) item.Retire();
foreach (var id in _projectedVariables.Keys) PredefinedNodes?.Remove(id);
foreach (var id in _projectedAnchors.Keys) PredefinedNodes?.Remove(id);
foreach (var (id, definition) in _projectedDefinitions) RetireProjectedCharge(id, definition.Lifetime);
foreach (var (id, anchor) in _projectedAnchors) RetireProjectedCharge(id, anchor.Definition.Lifetime);
_projectedVariables.Clear(); _projectedDefinitions.Clear(); _projectedSamples.Clear(); _projectedAnchors.Clear(); _projectedRootLeaves.Clear();
_projectedNodeCharges.Clear(); _projectedSampleCharges.Clear(); _projectedSampleBytes = 0;
Interlocked.Increment(ref _historyContinuationEpoch);
// Review 01 L2 — every monitored item on a node this rebuild discards is told and forgotten BEFORE
// the nodes go, so a later create on the same NodeId binds to the re-created node (see
@@ -4819,6 +5510,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
_eventNotifierSources.Clear();
ReconcileAllEventsMonitoring();
}
foreach (var proof in retiredProofs) proof.Invalidate();
}
// Reports ONE condition event for each native condition whose off-normal state the rebuild
@@ -5121,7 +5813,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
/// <returns><see langword="true"/> when this manager owns the node's namespace.</returns>
private bool OwnsNamespace(NodeId? nodeId) =>
nodeId is { } id
&& (id.NamespaceIndex == NamespaceIndexes[0] || id.NamespaceIndex == NamespaceIndexes[1]);
&& (id.NamespaceIndex == NamespaceIndexes[0] || id.NamespaceIndex == NamespaceIndexes[1] ||
id.NamespaceIndex == NamespaceIndexes[2] || id.NamespaceIndex == NamespaceIndexes[3]);
/// <summary>Pulls the ACL identity off an SDK operation context.</summary>
/// <param name="context">The SDK context carrying the session identity.</param>
@@ -5141,10 +5834,22 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
/// <param name="operation">The operation being attempted.</param>
/// <param name="nodeId">The target node.</param>
/// <returns><see langword="true"/> when permitted, or when the node is not ours to gate.</returns>
private bool Permits(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId) =>
!OwnsNamespace(nodeId)
|| _authorizer?.AuthorizeIfRequired(identity, operation, nodeId, RealmOf(nodeId)) is null
&& (_authorizer is not null || _mappedSubjectResolver is null);
private bool Permits(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId)
{
if (!OwnsNamespace(nodeId)) return true;
var realm = RealmOf(nodeId);
if (_projectedAnchors.TryGetValue(nodeId, out var anchor) && operation == OpcUaOperation.Browse)
{
if (!anchor.Definition.AuthorityIsCurrent()) return false;
var localId = new NodeId(anchor.Definition.LocalSubject, NamespaceIndexForRealm(realm));
return _authorizer?.AuthorizeIfRequired(identity, operation, localId, realm) is null &&
(_authorizer is not null || _mappedSubjectResolver is null);
}
if (nodeId.NamespaceIndex == NamespaceIndexes[2] || nodeId.NamespaceIndex == NamespaceIndexes[3])
return _authorizer is { } mappedAuthorizer && mappedAuthorizer.TryAuthorizeMapped(identity, operation, nodeId, realm, out var veto) && veto is null;
return _authorizer?.AuthorizeIfRequired(identity, operation, nodeId, realm) is null &&
(_authorizer is not null || _mappedSubjectResolver is null);
}
/// <summary>Guard against a corrupt (cyclic) parent chain in <see cref="ResolveUnsAclSubject"/>.</summary>
private const int MaxUnsAncestry = 64;
@@ -5329,6 +6034,53 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
var identity = IdentityOf(context);
var denied = 0;
for (var ii = 0; ii < nodesToRead.Count; ii++)
{
var projected = nodesToRead[ii];
if (projected.Processed || projected.AttributeId != Attributes.Value || !IsProjectedDescendant(projected.NodeId)) continue;
projected.Processed = true;
var access = ProjectedDataAccess;
IProjectedDemandLease? demand = null;
try
{
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);
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; }
}
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
values[ii] = new DataValue(Variant.Null, StatusCodes.BadWaitingForInitialData);
}
catch (Exception)
{
errors[ii] = StatusCodes.BadUserAccessDenied;
values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied);
}
finally { demand?.Dispose(); }
}
for (var ii = 0; ii < nodesToRead.Count; ii++)
{
var nodeToRead = nodesToRead[ii];
@@ -5368,6 +6120,33 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
ref ContinuationPoint continuationPoint,
IList<ReferenceDescription> references)
{
// A local mapping anchor remains visible in its parent; only browsing its remote
// children consults this nonblocking readiness snapshot.
var projectedParent = (continuationPoint?.NodeToBrowse as NodeHandle)?.NodeId;
if (projectedParent is not null && continuationPoint is not null && ProjectedBrowseAccess is { } browseAccess)
{
if (SecurityFilteringActive && !Permits(IdentityOf(context), OpcUaOperation.Browse, projectedParent.Value))
throw new ServiceResultException(StatusCodes.BadUserAccessDenied);
var result = browseAccess.GetOrSchedule(new(projectedParent.Value, IdentityOf(context), continuationPoint, ProjectedBrowseClock.GetTimestamp()));
if (result == global::ZB.MOM.WW.OtOpcUa.OpcUaServer.ProjectedBrowseReadiness.Pending)
throw new ServiceResultException(StatusCodes.BadWaitingForInitialData);
if (result == global::ZB.MOM.WW.OtOpcUa.OpcUaServer.ProjectedBrowseReadiness.Unavailable)
throw new ServiceResultException(StatusCodes.BadNoCommunication);
if (result == global::ZB.MOM.WW.OtOpcUa.OpcUaServer.ProjectedBrowseReadiness.InvalidContinuation)
throw new ServiceResultException(StatusCodes.BadContinuationPointInvalid);
}
if (projectedParent is not null && ProjectedBrowseReadiness is { } readiness)
{
if (SecurityFilteringActive && !Permits(IdentityOf(context), OpcUaOperation.Browse, projectedParent.Value))
throw new ServiceResultException(StatusCodes.BadUserAccessDenied);
var status = readiness(projectedParent.Value);
if (status == global::ZB.MOM.WW.OtOpcUa.OpcUaServer.ProjectedBrowseReadiness.Pending)
throw new ServiceResultException(StatusCodes.BadWaitingForInitialData);
if (status == global::ZB.MOM.WW.OtOpcUa.OpcUaServer.ProjectedBrowseReadiness.Unavailable)
throw new ServiceResultException(StatusCodes.BadNoCommunication);
if (status == global::ZB.MOM.WW.OtOpcUa.OpcUaServer.ProjectedBrowseReadiness.InvalidContinuation)
throw new ServiceResultException(StatusCodes.BadContinuationPointInvalid);
}
if (!SecurityFilteringActive)
{
base.Browse(context, ref continuationPoint!, references);
@@ -5498,6 +6277,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
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 (Permits(identity, OpcUaOperation.CreateMonitoredItems, target!.Value)) continue;
item.Processed = true;
@@ -5614,6 +6395,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
NodeHandle handle)
{
if (SecurityFilteringActive && monitoringMode != MonitoringMode.Disabled
&& !(monitoredItem is ProjectedMonitoredItem projected && projected.IsCurrent)
&& !Permits(IdentityOf(context), OpcUaOperation.CreateMonitoredItems, handle.NodeId))
{
return StatusCodes.BadUserAccessDenied;
@@ -5646,6 +6428,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
protected override void OnMonitoredItemDeleted(
ServerSystemContext context, NodeHandle handle, ISampledDataChangeMonitoredItem monitoredItem)
{
if (monitoredItem is ProjectedMonitoredItem projected) projected.Retire();
if (_liveItems.TryRemove(monitoredItem, out var tracked) && tracked.Suppressed) Interlocked.Decrement(ref _suppressedItems);
base.OnMonitoredItemDeleted(context, handle, monitoredItem);
}
@@ -5730,6 +6513,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
{
foreach (var item in dataItems.Values.ToArray())
{
if (item is ProjectedMonitoredItem projected) projected.Retire();
TellNodeRemoved(item, now);
if (item is ISampledDataChangeMonitoredItem sampled) _liveItems.TryRemove(sampled, out _);
ReleaseComponentCacheReference(item);
@@ -7456,8 +8240,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
if (item is not IMonitoredItem live) continue;
var nodeId = tracked.Handle.NodeId;
var permitted = IsSubscriptionStillPermitted(
live.EffectiveIdentity as RoleCarryingUserIdentity, nodeId, verdicts);
var permitted = item is ProjectedMonitoredItem projectedItem
? projectedItem.HasCurrentDemand
: IsSubscriptionStillPermitted(live.EffectiveIdentity as RoleCarryingUserIdentity, nodeId, verdicts);
if (permitted)
{
@@ -7470,7 +8255,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
bool reattached;
lock (Lock)
{
reattached = ResolveNodeState(MapKey(nodeId)) is { } liveNode
reattached = (item is ProjectedMonitoredItem
? (GetManagerHandle(nodeId) as NodeHandle)?.Node
: ResolveNodeState(MapKey(nodeId))) is { } liveNode
&& ReferenceEquals(liveNode, tracked.Handle.Node);
if (reattached) tracked.Handle.MonitoredNode?.Add(item);
else _liveItems.TryRemove(item, out _);
@@ -7479,6 +8266,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
Interlocked.Decrement(ref _suppressedItems);
if (!reattached)
{
if (item is ProjectedMonitoredItem projected) projected.Retire();
TellNodeRemoved(item, now);
continue;
}
@@ -6,6 +6,9 @@ using Opc.Ua.Server.Hosting;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using DataBudget = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataBudget;
using DataOperations = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataOperations;
using DataWriteState = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataWriteState;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
@@ -373,6 +376,363 @@ public sealed class OtOpcUaSdkServer : StandardServer
return ids;
}
/// <summary>Dispatch mapped writes asynchronously without mutating the SDK value optimistically.</summary>
public override async ValueTask<WriteResponse> WriteAsync(SecureChannelContext secureChannelContext, RequestHeader? requestHeader,
ArrayOf<WriteValue> nodesToWrite, RequestLifetime requestLifetime)
{
var manager = _otOpcUaNodeManager;
var containsProjected = false;
if (manager is not null)
for (var i = 0; i < nodesToWrite.Count; i++)
if (manager.IsProjectedItem(nodesToWrite[i].NodeId)) { containsProjected = true; break; }
if (manager is null || !containsProjected)
return await base.WriteAsync(secureChannelContext, requestHeader, nodesToWrite, requestLifetime).ConfigureAwait(false);
var access = manager.ProjectedDataAccess;
var started = access?.Clock.GetTimestamp() ?? 0;
using var context = await ValidateRequestAsync(secureChannelContext, requestHeader, RequestType.Write, requestLifetime).ConfigureAwait(false);
try
{
ValidateOperationLimits(nodesToWrite, ServerInternal.ServerObject?.ServerCapabilities?.OperationLimits?.MaxNodesPerWrite);
var result = new StatusCode[nodesToWrite.Count];
var legacy = new List<WriteValue>();
var legacyIndexes = new List<int>();
var caller = context.UserIdentity as RoleCarryingUserIdentity;
for (var i = 0; i < nodesToWrite.Count; i++)
{
var item = nodesToWrite[i];
if (!manager.IsProjectedItem(item.NodeId)) { legacy.Add(item); legacyIndexes.Add(i); continue; }
if (!manager.CanDispatchProjectedWrite()) { result[i] = StatusCodes.BadInvalidState; continue; }
if (item.AttributeId != Attributes.Value || !string.IsNullOrEmpty(item.IndexRange) ||
item.Value.StatusCode.Code != StatusCodes.Good.Code || item.Value.SourceTimestamp != DateTimeUtc.MinValue ||
item.Value.ServerTimestamp != DateTimeUtc.MinValue)
{ result[i] = StatusCodes.BadWriteNotSupported; continue; }
IProjectedDemandLease? demand = null;
try
{
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; }
if (!manager.CanDispatchProjectedWrite()) { result[i] = StatusCodes.BadInvalidState; continue; }
var milliseconds = requestHeader is { TimeoutHint: > 0 } ? Math.Min(requestHeader.TimeoutHint, 5000u) : 5000u;
var budget = new DataBudget(TimeSpan.FromMilliseconds(milliseconds), 1, 4 * 1024 * 1024);
var outcome = await access.WriteAsync(demand, SdkValueBoundary.ToClr(item.Value.WrappedValue), budget, started,
requestLifetime.CancellationToken).ConfigureAwait(false);
result[i] = outcome.State switch
{
DataWriteState.DriverConfirmedSuccess when demand.IsValid => StatusCodes.Good,
DataWriteState.AcceptedUnconfirmed or DataWriteState.OutcomeUnknown or DataWriteState.DriverConfirmedSuccess => StatusCodes.UncertainLastUsableValue,
_ => StatusCode.IsBad(outcome.StatusCode) ? outcome.StatusCode : StatusCodes.BadNotWritable
};
}
catch (OperationCanceledException) { result[i] = StatusCodes.UncertainLastUsableValue; }
catch (Exception) { result[i] = StatusCodes.UncertainLastUsableValue; }
finally { demand?.Dispose(); }
}
if (legacy.Count > 0)
{
var (statuses, _) = await ServerInternal.NodeManager.WriteAsync(context, legacy.ToArray(), requestLifetime.CancellationToken).ConfigureAwait(false);
for (var i = 0; i < legacyIndexes.Count; i++) result[legacyIndexes[i]] = statuses[i];
}
return new WriteResponse { Results = result, ResponseHeader = CreateResponse(requestHeader, context.StringTable) };
}
finally { OnRequestComplete(context); }
}
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;
private long _maxProjectedBrowseBytes = 16 * 1024 * 1024;
private int _projectedBrowseRetained;
private long _projectedBrowseRetainedBytes;
/// <summary>Sets aggregate cursor count and retained-byte limits before cursors are created.</summary>
public void SetProjectedBrowseLimits(int maxCursors, long maxBytes)
{
if (maxCursors <= 0 || maxBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxCursors));
lock (_projectedBrowseLock)
{
if (_projectedBrowseRetained != 0) throw new InvalidOperationException("Projected browse cursors are active.");
_maxProjectedBrowseCursors = maxCursors; _maxProjectedBrowseBytes = maxBytes;
}
}
private const int MaxProjectedBrowseChildren = 4096;
private sealed record ProjectedBrowseFilter(BrowseDirection Direction, NodeId ReferenceType, bool IncludeSubtypes,
uint NodeClassMask, uint ResultMask, ViewDescription? View);
private sealed class ProjectedBrowseCursor(NodeId parent, NodeId session, DataCallerIdentity caller,
ProjectedBrowsePage page, int index, uint maximum, long expires, ProjectedBrowseFilter filter)
{
public NodeId Parent = parent;
public NodeId Session = session;
public DataCallerIdentity Caller = caller;
public ProjectedBrowsePage Page = page;
public int Index = index;
public uint Maximum = maximum;
public long Expires = expires;
public ProjectedBrowseFilter Filter = filter;
public long Charge;
public bool Transferred;
public bool Released;
}
private static bool TryProjectedCursor(ByteString token, out Guid id)
{
id = default;
var bytes = token.ToArray();
if (bytes is null || bytes.Length != 24 || !bytes.AsSpan(0, 8).SequenceEqual(ProjectedCursorPrefix)) return false;
id = new Guid(bytes.AsSpan(8, 16));
return true;
}
private static ByteString EncodeProjectedCursor(Guid id)
{
var bytes = new byte[24];
ProjectedCursorPrefix.CopyTo(bytes, 0);
id.TryWriteBytes(bytes.AsSpan(8));
return ByteString.From(bytes);
}
private void ReleaseProjectedCursor(ProjectedBrowseCursor cursor)
{
lock (_projectedBrowseLock)
{
if (cursor.Released || cursor.Transferred) return;
cursor.Released = true;
_projectedBrowseRetained--; _projectedBrowseRetainedBytes -= cursor.Charge;
}
}
private ByteString SaveProjectedCursor(ProjectedBrowseCursor cursor, TimeProvider clock, ProjectedBrowseCursor? replacing)
{
long charge;
try
{
charge = checked(4096L + Math.Max(0, cursor.Page.RetainedBytes) + 2L * (cursor.Page.NextCursor?.Length ?? 0) +
cursor.Page.Children.Sum(child => 128L + 2L * child.IdentifierAsString.Length));
}
catch (OverflowException) { return default; }
lock (_projectedBrowseLock)
{
var now = clock.GetTimestamp();
foreach (var expired in _projectedBrowseCursors.Where(pair => pair.Value.Expires <= now).Select(pair => pair.Key).ToArray())
if (_projectedBrowseCursors.Remove(expired, out var removed)) ReleaseProjectedCursor(removed);
var oldCharge = replacing is { Released: false, Transferred: false } ? replacing.Charge : 0;
if ((oldCharge == 0 && _projectedBrowseRetained >= _maxProjectedBrowseCursors) ||
charge > _maxProjectedBrowseBytes - _projectedBrowseRetainedBytes + oldCharge) return default;
var id = Guid.NewGuid();
cursor.Charge = charge;
_projectedBrowseCursors.Add(id, cursor);
if (oldCharge == 0) _projectedBrowseRetained++;
else replacing!.Transferred = true;
_projectedBrowseRetainedBytes += charge - oldCharge;
return EncodeProjectedCursor(id);
}
}
private void UndoProjectedCursor(Guid id, ProjectedBrowseCursor? replacing)
{
lock (_projectedBrowseLock)
{
if (!_projectedBrowseCursors.Remove(id, out var created)) return;
if (replacing is { Transferred: true, Released: false })
{
replacing.Transferred = false;
created.Released = true;
_projectedBrowseRetainedBytes += replacing.Charge - created.Charge;
}
else ReleaseProjectedCursor(created);
}
}
private static bool ProjectedPageCurrent(ProjectedBrowsePage page)
{ try { return page.IsCurrent(); } catch (Exception) { return false; } }
private static DataCallerIdentity BrowseCaller(RoleCarryingUserIdentity caller) =>
new(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
private static long BrowseExpiry(TimeProvider clock)
{
var now = clock.GetTimestamp();
var frequency = clock.TimestampFrequency;
var duration = frequency > long.MaxValue / 60 ? long.MaxValue : frequency * 60;
return now > long.MaxValue - duration ? long.MaxValue : now + duration;
}
private static bool MatchesProjectedClass(ReferenceDescription reference, uint mask) => mask == 0 || (mask & (uint)reference.NodeClass) != 0;
private static ReferenceDescription MaskProjectedReference(ReferenceDescription reference, uint mask)
{
if ((mask & (uint)BrowseResultMask.ReferenceTypeId) == 0) reference.ReferenceTypeId = default;
if ((mask & (uint)BrowseResultMask.IsForward) == 0) reference.IsForward = false;
if ((mask & (uint)BrowseResultMask.NodeClass) == 0) reference.NodeClass = NodeClass.Unspecified;
if ((mask & (uint)BrowseResultMask.BrowseName) == 0) reference.BrowseName = default;
if ((mask & (uint)BrowseResultMask.DisplayName) == 0) reference.DisplayName = default;
if ((mask & (uint)BrowseResultMask.TypeDefinition) == 0) reference.TypeDefinition = default;
return reference;
}
private async Task<BrowseResult> ReadProjectedPageAsync(OtOpcUaNodeManager manager, RoleCarryingUserIdentity caller,
NodeId session, ProjectedBrowseCursor? cursor, NodeId parent, uint maximum, ProjectedBrowseFilter filter,
long started, CancellationToken cancellationToken)
{
var access = manager.ProjectedBrowseAccess;
if (access is null) return new BrowseResult { StatusCode = StatusCodes.BadNoCommunication };
if (!manager.CanBrowseProjectedParent(parent, caller)) return new BrowseResult { StatusCode = StatusCodes.BadUserAccessDenied };
var limit = maximum == 0 ? MaxProjectedBrowseChildren : (int)Math.Min(maximum, MaxProjectedBrowseChildren);
var references = new List<ReferenceDescription>();
if (cursor is null && (filter.Direction is BrowseDirection.Inverse or BrowseDirection.Both) &&
manager.TryDescribeProjectedParent(parent, caller, out var inverse) && inverse is not null && MatchesProjectedClass(inverse, filter.NodeClassMask))
references.Add(MaskProjectedReference(inverse, filter.ResultMask));
if (filter.Direction == BrowseDirection.Inverse)
return manager.CanBrowseProjectedParent(parent, caller)
? new BrowseResult { StatusCode = StatusCodes.Good, References = references.ToArray() }
: new BrowseResult { StatusCode = StatusCodes.BadUserAccessDenied };
var page = cursor?.Page;
var index = cursor?.Index ?? 0;
if (page is null || (index >= page.Children.Count && !page.Complete))
{
var next = page?.NextCursor;
if (page is not null && string.IsNullOrEmpty(next)) return new BrowseResult { StatusCode = StatusCodes.BadContinuationPointInvalid };
page = await access.WaitForPageAsync(new(parent, caller, next, maximum, started), cancellationToken).ConfigureAwait(false);
index = 0;
}
if (cursor is not null && cursor.Expires <= manager.ProjectedBrowseClock.GetTimestamp())
return new BrowseResult { StatusCode = StatusCodes.BadContinuationPointInvalid };
if (page.Status != ProjectedBrowseReadiness.Ready)
return new BrowseResult { StatusCode = page.Status switch
{
ProjectedBrowseReadiness.Pending => StatusCodes.BadWaitingForInitialData,
ProjectedBrowseReadiness.InvalidContinuation => StatusCodes.BadContinuationPointInvalid,
_ => StatusCodes.BadNoCommunication
} };
if (page.Children.Count > MaxProjectedBrowseChildren || page.Children.Sum(child => (long)child.IdentifierAsString.Length) > 2 * 1024 * 1024 || page.NextCursor?.Length > 16_384 ||
(!page.Complete && string.IsNullOrEmpty(page.NextCursor)) || !ProjectedPageCurrent(page))
return new BrowseResult { StatusCode = StatusCodes.BadNoCommunication };
while (index < page.Children.Count && references.Count < limit)
{
if (!ProjectedPageCurrent(page)) return new BrowseResult { StatusCode = StatusCodes.BadNoCommunication };
var child = page.Children[index++];
if (manager.TryDescribeProjectedChild(child, caller, out var reference) && reference is not null && MatchesProjectedClass(reference, filter.NodeClassMask))
references.Add(MaskProjectedReference(reference, filter.ResultMask));
}
if (cursor is not null && cursor.Expires <= manager.ProjectedBrowseClock.GetTimestamp())
return new BrowseResult { StatusCode = StatusCodes.BadContinuationPointInvalid };
if (!manager.CanBrowseProjectedParent(parent, caller) || !ProjectedPageCurrent(page)) return new BrowseResult { StatusCode = StatusCodes.BadNoCommunication };
var result = new BrowseResult { StatusCode = StatusCodes.Good, References = references.ToArray() };
if (index < page.Children.Count || !page.Complete)
{
var state = new ProjectedBrowseCursor(parent, session, BrowseCaller(caller), page, index, maximum, BrowseExpiry(manager.ProjectedBrowseClock), filter);
result.ContinuationPoint = SaveProjectedCursor(state, manager.ProjectedBrowseClock, cursor);
if (result.ContinuationPoint.IsEmpty) result.StatusCode = StatusCodes.BadNoContinuationPoints;
else if (!ProjectedPageCurrent(page))
{
if (TryProjectedCursor(result.ContinuationPoint, out var retired)) UndoProjectedCursor(retired, cursor);
return new BrowseResult { StatusCode = StatusCodes.BadNoCommunication };
}
}
return result;
}
/// <summary>Browse mapped pages asynchronously, preserving the SDK path for local nodes.</summary>
public override async ValueTask<BrowseResponse> BrowseAsync(SecureChannelContext secureChannelContext, RequestHeader? requestHeader,
ViewDescription? view, uint requestedMaxReferencesPerNode, ArrayOf<BrowseDescription> nodesToBrowse, RequestLifetime requestLifetime)
{
var manager = _otOpcUaNodeManager;
var projected = false;
if (manager is not null)
for (var i = 0; i < nodesToBrowse.Count; i++) if (manager.IsProjectedBrowseNode(nodesToBrowse[i].NodeId)) { projected = true; break; }
if (!projected || manager is null) return await base.BrowseAsync(secureChannelContext, requestHeader, view,
requestedMaxReferencesPerNode, nodesToBrowse, requestLifetime).ConfigureAwait(false);
var started = manager.ProjectedBrowseClock.GetTimestamp();
using var context = await ValidateRequestAsync(secureChannelContext, requestHeader, RequestType.Browse, requestLifetime).ConfigureAwait(false);
try
{
ValidateOperationLimits(nodesToBrowse, ServerInternal.ServerObject?.ServerCapabilities?.OperationLimits?.MaxNodesPerBrowse);
var results = new BrowseResult[nodesToBrowse.Count];
var legacy = new List<BrowseDescription>(); var indexes = new List<int>();
var caller = context.UserIdentity as RoleCarryingUserIdentity;
for (var i = 0; i < nodesToBrowse.Count; i++)
{
var request = nodesToBrowse[i];
if (!manager.IsProjectedBrowseNode(request.NodeId)) { legacy.Add(request); indexes.Add(i); continue; }
if (caller is null || context.Session is null)
{ results[i] = new BrowseResult { StatusCode = StatusCodes.BadUserAccessDenied }; continue; }
if (request.BrowseDirection is not (BrowseDirection.Forward or BrowseDirection.Inverse or BrowseDirection.Both))
{ results[i] = new BrowseResult { StatusCode = StatusCodes.BadBrowseDirectionInvalid }; continue; }
var viewError = manager.ValidateProjectedView(context, view);
if (viewError is not null) { results[i] = new BrowseResult { StatusCode = viewError.StatusCode }; continue; }
if (!request.ReferenceTypeId.IsNull && ServerInternal.TypeTree.FindReferenceTypeName(request.ReferenceTypeId).IsNull)
{ results[i] = new BrowseResult { StatusCode = StatusCodes.BadReferenceTypeIdInvalid }; continue; }
var matchesReference = request.ReferenceTypeId.IsNull || request.ReferenceTypeId == ReferenceTypeIds.Organizes ||
(request.IncludeSubtypes && ServerInternal.TypeTree.IsTypeOf(ReferenceTypeIds.Organizes, request.ReferenceTypeId));
if (!matchesReference) { results[i] = new BrowseResult { StatusCode = StatusCodes.Good }; continue; }
var copiedView = view is null ? null : new ViewDescription { ViewId = view.ViewId, Timestamp = view.Timestamp, ViewVersion = view.ViewVersion };
var filter = new ProjectedBrowseFilter(request.BrowseDirection, request.ReferenceTypeId, request.IncludeSubtypes,
request.NodeClassMask, request.ResultMask, copiedView);
results[i] = await ReadProjectedPageAsync(manager, caller, context.SessionId, null, request.NodeId,
requestedMaxReferencesPerNode, filter, started, requestLifetime.CancellationToken).ConfigureAwait(false);
}
if (legacy.Count > 0)
{
var (other, _) = await ServerInternal.NodeManager.BrowseAsync(context, view ?? new ViewDescription(), requestedMaxReferencesPerNode,
legacy.ToArray(), requestLifetime.CancellationToken).ConfigureAwait(false);
for (var i = 0; i < indexes.Count; i++) results[indexes[i]] = other[i];
}
return new BrowseResponse { Results = results, ResponseHeader = CreateResponse(requestHeader, context.StringTable) };
}
finally { OnRequestComplete(context); }
}
/// <summary>BrowseNext for SDK-owned projected cursors, retaining standard handling for other tokens.</summary>
public override async ValueTask<BrowseNextResponse> BrowseNextAsync(SecureChannelContext secureChannelContext, RequestHeader? requestHeader,
bool releaseContinuationPoints, ArrayOf<ByteString> continuationPoints, RequestLifetime requestLifetime)
{
var manager = _otOpcUaNodeManager;
var projected = false;
for (var i = 0; i < continuationPoints.Count; i++) if (TryProjectedCursor(continuationPoints[i], out _)) { projected = true; break; }
if (!projected || manager is null) return await base.BrowseNextAsync(secureChannelContext, requestHeader,
releaseContinuationPoints, continuationPoints, requestLifetime).ConfigureAwait(false);
var started = manager.ProjectedBrowseClock.GetTimestamp();
using var context = await ValidateRequestAsync(secureChannelContext, requestHeader, RequestType.BrowseNext, requestLifetime).ConfigureAwait(false);
try
{
ValidateOperationLimits(continuationPoints, ServerInternal.ServerObject?.ServerCapabilities?.OperationLimits?.MaxNodesPerBrowse);
var results = new BrowseResult[continuationPoints.Count];
var legacy = new List<ByteString>(); var indexes = new List<int>();
var caller = context.UserIdentity as RoleCarryingUserIdentity;
for (var i = 0; i < continuationPoints.Count; i++)
{
var token = continuationPoints[i];
if (!TryProjectedCursor(token, out var id)) { legacy.Add(token); indexes.Add(i); continue; }
ProjectedBrowseCursor? state = null;
lock (_projectedBrowseLock)
{
if (caller is not null && context.Session is not null && _projectedBrowseCursors.TryGetValue(id, out var candidate) &&
candidate.Session == context.SessionId && candidate.Caller == BrowseCaller(caller) &&
candidate.Expires > manager.ProjectedBrowseClock.GetTimestamp())
{ state = candidate; _projectedBrowseCursors.Remove(id); }
}
if (state is null || caller is null) { results[i] = new BrowseResult { StatusCode = StatusCodes.BadContinuationPointInvalid }; continue; }
if (releaseContinuationPoints) { ReleaseProjectedCursor(state); results[i] = new BrowseResult { StatusCode = StatusCodes.Good }; continue; }
var viewError = manager.ValidateProjectedView(context, state.Filter.View);
if (viewError is not null) { ReleaseProjectedCursor(state); results[i] = new BrowseResult { StatusCode = viewError.StatusCode }; continue; }
try
{
results[i] = await ReadProjectedPageAsync(manager, caller, context.SessionId, state, state.Parent, state.Maximum, state.Filter,
started, requestLifetime.CancellationToken).ConfigureAwait(false);
if (StatusCode.IsBad(results[i].StatusCode) && state.Expires > manager.ProjectedBrowseClock.GetTimestamp())
lock (_projectedBrowseLock) _projectedBrowseCursors.TryAdd(id, state);
else ReleaseProjectedCursor(state);
}
catch
{
lock (_projectedBrowseLock) _projectedBrowseCursors.TryAdd(id, state);
throw;
}
}
if (legacy.Count > 0)
{
var (other, _) = await ServerInternal.NodeManager.BrowseNextAsync(context, releaseContinuationPoints, legacy.ToArray(),
requestLifetime.CancellationToken).ConfigureAwait(false);
for (var i = 0; i < indexes.Count; i++) results[indexes[i]] = other[i];
}
return new BrowseNextResponse { Results = results, ResponseHeader = CreateResponse(requestHeader, context.StringTable) };
}
finally { OnRequestComplete(context); }
}
private long _publishesSinceSweep;
/// <inheritdoc />
@@ -382,6 +742,8 @@ public sealed class OtOpcUaSdkServer : StandardServer
{
var response = await base.PublishAsync(secureChannelContext, requestHeader, subscriptionAcknowledgements, requestLifetime)
.ConfigureAwait(false);
if (response?.NotificationMessage is { } projectedMessage)
response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: false);
if (_standby.Delivery is not { } record || response?.NotificationMessage is not { } message) return response!;
if (message.NotificationData.Count > 0)
@@ -402,6 +764,8 @@ public sealed class OtOpcUaSdkServer : StandardServer
{
var response = await base.RepublishAsync(secureChannelContext, requestHeader, subscriptionId, retransmitSequenceNumber,
requestLifetime).ConfigureAwait(false);
if (response?.NotificationMessage is { } projectedMessage)
response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: true);
if (_standby.Delivery is { } record && response?.NotificationMessage is { NotificationData.Count: > 0 } message)
response.NotificationMessage = Decide(record, subscriptionId, message);
return response!;
@@ -0,0 +1,44 @@
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>SDK-owned, session-bound peer cursor; it does not expose or own the peer token to the client.</summary>
internal sealed class ProjectedBrowseContinuation : IDisposable
{
private readonly object _sync = new();
private readonly NodeId _parent;
private readonly NodeId _session;
private readonly DataCallerIdentity _caller;
private string? _cursor;
private bool _disposed;
public ProjectedBrowseContinuation(NodeId parent, NodeId session, RoleCarryingUserIdentity caller, string? cursor)
{
_parent = parent; _session = session;
_caller = new(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
_cursor = cursor;
}
public bool TryGetCursor(NodeId parent, NodeId session, RoleCarryingUserIdentity caller, out string? cursor)
{
lock (_sync)
{
if (!_disposed && parent == _parent && session == _session &&
_caller == new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc))
{ cursor = _cursor; return true; }
cursor = null; return false;
}
}
public bool TryAdvance(string? expectedCursor, string? nextCursor, Func<bool> commit)
{
ArgumentNullException.ThrowIfNull(commit);
lock (_sync)
{
if (_disposed || _cursor != expectedCursor || !commit()) return false;
_cursor = nextCursor;
return true;
}
}
public void Dispose() { lock (_sync) { _disposed = true; _cursor = null; } }
}
@@ -0,0 +1,36 @@
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>Shared retained-candidate accounting across projected monitored items.</summary>
internal sealed class ProjectedCandidateBudget
{
private readonly object _sync = new();
private readonly int _maxEntries;
private readonly long _maxBytes;
private int _entries;
private long _bytes;
public ProjectedCandidateBudget(int maxEntries, long maxBytes)
{
if (maxEntries <= 0 || maxBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxEntries));
_maxEntries = maxEntries; _maxBytes = maxBytes;
}
public long RetainedBytes { get { lock (_sync) return _bytes; } }
public int RetainedEntries { get { lock (_sync) return _entries; } }
public bool TryReserve(long bytes, out IDisposable? lease)
{
lease = null;
if (bytes <= 0) return false;
lock (_sync)
{
if (_entries >= _maxEntries || bytes > _maxBytes - _bytes) return false;
_entries++; _bytes += bytes;
lease = new Reservation(this, bytes);
return true;
}
}
private void Release(long bytes) { lock (_sync) { _entries--; _bytes -= bytes; } }
private sealed class Reservation(ProjectedCandidateBudget owner, long bytes) : IDisposable
{
private int _released;
public void Dispose() { if (Interlocked.Exchange(ref _released, 1) == 0) owner.Release(bytes); }
}
}
@@ -0,0 +1,56 @@
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>A pin on one exact SDK materialization incarnation.</summary>
public interface IProjectedNodePin : IDisposable { bool IsValid { get; } }
/// <summary>Atomically fences idle retirement against new demand.</summary>
public sealed class ProjectedNodeLifetime
{
private readonly object _sync = new();
private int _pins;
private bool _retired;
private Action? _drained;
public bool TryPin(out IProjectedNodePin? pin)
{
lock (_sync)
{
if (_retired) { pin = null; return false; }
checked { _pins++; }
pin = new Pin(this);
return true;
}
}
public bool TryRetire()
{
lock (_sync) { if (_retired || _pins != 0) return false; _retired = true; return true; }
}
public void ForceRetire() => ForceRetire(null);
internal void ForceRetire(Action? drained)
{
Action? ready = null;
lock (_sync)
{
_retired = true;
_drained += drained;
if (_pins == 0) { ready = _drained; _drained = null; }
}
ready?.Invoke();
}
public bool IsActive { get { lock (_sync) return !_retired; } }
private void Release()
{
Action? ready = null;
lock (_sync)
{
_pins--;
if (_retired && _pins == 0) { ready = _drained; _drained = null; }
}
ready?.Invoke();
}
private sealed class Pin(ProjectedNodeLifetime owner) : IProjectedNodePin
{
private int _disposed;
public bool IsValid => Volatile.Read(ref _disposed) == 0 && owner.IsActive;
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) owner.Release(); }
}
}
@@ -1,4 +1,6 @@
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
@@ -8,7 +10,7 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <see cref="OtOpcUaNodeManager"/>. The host wires this in once the StandardServer has
/// been started (so the node manager exists).
/// </summary>
public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddressSpaceSink
public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddressSpaceSink, IProjectedValueSink, IProjectedNamespacePageSink, IProjectedNodeLookup, IProjectedAnchorSink
{
private readonly OtOpcUaNodeManager _nodeManager;
@@ -20,6 +22,32 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre
_nodeManager = nodeManager;
}
/// <inheritdoc />
public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) => _nodeManager.TryResolve(nodeId, out definition);
/// <inheritdoc />
public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) => _nodeManager.TryGetNodeId(namespaceUri, identifier, out nodeId);
/// <inheritdoc />
public bool TryEnsureProjectedAnchor(ProjectedAnchorDefinition definition, out NodeId? nodeId) => _nodeManager.TryEnsureProjectedAnchor(definition, out nodeId);
/// <inheritdoc />
public bool TryRemoveProjectedAnchor(NodeId nodeId, ProjectedAnchorDefinition expected) => _nodeManager.TryRemoveProjectedAnchor(nodeId, expected);
/// <inheritdoc />
public bool TryApplyRootLeaf(NodeId anchorId, ProjectedVariableDefinition rootDefinition, Func<bool> commit) =>
((IProjectedNamespacePageSink)_nodeManager).TryApplyRootLeaf(anchorId, rootDefinition, commit);
/// <inheritdoc />
public bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected) => ((IProjectedNamespacePageSink)_nodeManager).TryRemove(nodeId, expected);
/// <inheritdoc />
public bool TryApply(NodeId parent, IReadOnlyList<ProjectedVariableDefinition> nodes, Func<bool> commit) =>
((IProjectedNamespacePageSink)_nodeManager).TryApply(parent, nodes, commit);
/// <inheritdoc />
public bool TryPublish(IReadOnlyList<ProjectedValueWrite> values) => ((IProjectedValueSink)_nodeManager).TryPublish(values);
/// <inheritdoc />
public void WriteValue(string nodeId, object? value, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm)
=> _nodeManager.WriteValue(nodeId, value, statusCode, sourceTimestampUtc, realm);
@@ -141,6 +141,9 @@ public sealed class DataPlaneAuthorizer
/// <summary>Live catalog classification owned by the node manager, consulted before either local path resolver.</summary>
public Func<AddressSpaceRealm, string, MappedNodeResolution>? MappedSubjectResolver { get; set; }
/// <summary>Optional actual-namespace filter for projected subject classification.</summary>
public Func<NodeId, bool>? MappedNamespacePredicate { get; set; }
/// <summary>Checks a mapped subject even when local ACL enforcement is disabled.</summary>
public ServiceResult? AuthorizeIfRequired(RoleCarryingUserIdentity? identity, OpcUaOperation operation,
NodeId nodeId, AddressSpaceRealm realm, bool cached = true) =>
@@ -151,6 +154,7 @@ public sealed class DataPlaneAuthorizer
NodeId nodeId, AddressSpaceRealm realm, out ServiceResult? veto)
{
var resolver = MappedSubjectResolver;
if (MappedNamespacePredicate is { } predicate && !predicate(nodeId)) { veto = null; return false; }
if (resolver is null) { veto = null; return false; }
if (!nodeId.TryGetValue(out string identifier) || identifier.Length == 0 || identifier.Contains('\0'))
{ veto = DeniedResult; return true; }
@@ -1,6 +1,8 @@
using Microsoft.Extensions.Logging;
using Opc.Ua;
using Opc.Ua.Server;
using DataValue = Opc.Ua.DataValue;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
@@ -325,7 +327,7 @@ internal sealed class OrdinaryTagMonitoredItem : MonitoredItem
/// its internal lifecycle interface keep working (T0c; the 2.0.1 <c>MonitoredItemFactory</c> hook exists only on
/// <c>AsyncCustomNodeManager</c>). Installed only under Warm; <c>Unset</c>/<c>None</c> keep the SDK's manager.
/// </summary>
internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, IServerInternal server)
internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, IServerInternal server, OtOpcUaNodeManager owner, bool warmMode)
: MonitoredNodeMonitoredItemManager(nodeManager, server), IMonitoredItemManager
{
/// <inheritdoc />
@@ -335,13 +337,22 @@ internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, ISer
Opc.Ua.Range euRange, MonitoringFilter filterToUse, double samplingInterval, uint revisedQueueSize, bool createDurable,
MonitoredItemIdFactory monitoredItemIdFactory, Func<ISystemContext, NodeHandle, NodeState, NodeState> addNodeToComponentCache)
{
if (handle.Node is not EquipmentVariableState || itemToCreate.ItemToMonitor.AttributeId != Attributes.Value)
var projected = owner.IsProjectedItem(handle.NodeId) && itemToCreate.ItemToMonitor.AttributeId == Attributes.Value;
if (!projected && (!warmMode || handle.Node is not EquipmentVariableState || itemToCreate.ItemToMonitor.AttributeId != Attributes.Value))
{
return CreateMonitoredItem(server, nodeManager, context, handle, subscriptionId, publishingInterval, diagnosticsMasks,
timestampsToReturn, itemToCreate, euRange, filterToUse, samplingInterval, revisedQueueSize, createDurable,
monitoredItemIdFactory, addNodeToComponentCache);
}
IProjectedDemandLease? demand = null;
ProjectedValueWrite? initialSample = null;
ProjectedVariableDefinition? definition = null;
if (projected && !owner.TryAcquireProjectedItem(context, handle.NodeId, publishingInterval, out demand, out initialSample, out definition))
throw new ServiceResultException(StatusCodes.BadUserAccessDenied);
uint? reservedId = null;
try
{
// Mirrors MonitoredNodeMonitoredItemManager.CreateMonitoredItem in exact tagged 2.0.1, swapping only the item type.
var cachedNode = addNodeToComponentCache(context, handle, handle.Node);
if (!MonitoredNodes.TryGetValue(handle.Node.NodeId, out var monitoredNode))
@@ -358,12 +369,222 @@ internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, ISer
id = monitoredItemIdFactory.GetNextId();
}
while (!MonitoredItems.TryAdd(id, null!));
reservedId = id;
var item = new OrdinaryTagMonitoredItem(server, nodeManager, handle, subscriptionId, id, itemToCreate, diagnosticsMasks,
timestampsToReturn, filterToUse, euRange, samplingInterval, revisedQueueSize, createDurable);
ISampledDataChangeMonitoredItem item = projected
? new ProjectedMonitoredItem(server, nodeManager, handle, subscriptionId, id, itemToCreate, diagnosticsMasks,
timestampsToReturn, filterToUse, euRange, samplingInterval, revisedQueueSize, createDurable,
owner, demand!, initialSample, definition!)
: new OrdinaryTagMonitoredItem(server, nodeManager, handle, subscriptionId, id, itemToCreate, diagnosticsMasks,
timestampsToReturn, filterToUse, euRange, samplingInterval, revisedQueueSize, createDurable);
monitoredNode.Add((IDataChangeMonitoredItem2)item);
if (item is ProjectedMonitoredItem projectedItem) owner.ObserveCurrentProjectedSource(projectedItem);
MonitoredItems[id] = item;
demand = null;
return item;
}
catch
{
if (reservedId is { } id) MonitoredItems.TryRemove(id, out _);
demand?.Dispose();
throw;
}
}
}
/// <summary>A projected item retains its original caller, item lifetime and source proof.</summary>
internal sealed class ProjectedMonitoredItem : MonitoredItem
{
private readonly OtOpcUaNodeManager _owner;
private IProjectedDemandLease? _demand;
private ProjectedVariableDefinition? _definition;
private readonly NodeId _nodeId;
private sealed class SourceBinding(IProjectedSamplePublicationProof proof)
{
private readonly object _sync = new();
private IProjectedSamplePublicationProof? _proof = proof;
private readonly List<WeakReference<SampleEvidence>> _evidence = [];
public IProjectedSamplePublicationProof? Proof { get { lock (_sync) return _proof; } }
public bool IsValid => Proof is { IsSourceValid: true };
public SampleEvidence? Capture(IProjectedSamplePublicationProof sample, DataAgeBounds age, long timestamp)
{
lock (_sync)
{
if (_proof is null) return null;
_evidence.RemoveAll(entry => !entry.TryGetTarget(out _));
if (_evidence.Count >= 4096) return null;
var evidence = new SampleEvidence(this, sample, age, timestamp);
_evidence.Add(new(evidence));
return evidence;
}
}
public void Retire()
{
lock (_sync)
{
_proof = null;
foreach (var entry in _evidence) if (entry.TryGetTarget(out var evidence)) evidence.Clear();
_evidence.Clear();
}
}
}
private sealed record Candidate(ProjectedValueWrite Sample, Variant Value, SourceBinding Binding, long Bytes, IDisposable Charge);
private sealed class SampleEvidence(SourceBinding binding, IProjectedSamplePublicationProof proof, DataAgeBounds age, long receivedTimestamp)
{
private IProjectedSamplePublicationProof? _proof = proof;
public SourceBinding Binding => binding;
public IProjectedSamplePublicationProof? Proof => Volatile.Read(ref _proof);
public DataAgeBounds Age => age;
public long ReceivedTimestamp => receivedTimestamp;
public void Clear() => Interlocked.Exchange(ref _proof, null);
}
private const int MaxCandidates = 1024;
private const long MaxCandidateBytes = 1024 * 1024;
private readonly object _bindingSync = new();
private readonly List<Candidate> _candidates = [];
private long _candidateBytes;
private bool _needsSnapshot;
private int _snapshotRequested;
private SourceBinding? _binding;
private int _retired;
private int _released;
public ProjectedMonitoredItem(IServerInternal server, IAsyncNodeManager nodeManager, NodeHandle handle, uint subscriptionId,
uint id, MonitoredItemCreateRequest request, DiagnosticsMasks masks, TimestampsToReturn timestamps,
MonitoringFilter? filter, Opc.Ua.Range? range, double samplingInterval, uint queueSize, bool durable,
OtOpcUaNodeManager owner, IProjectedDemandLease demand, ProjectedValueWrite? initialSample, ProjectedVariableDefinition definition)
: base(server, nodeManager, handle, subscriptionId, id, request.ItemToMonitor, masks, timestamps,
request.MonitoringMode, request.RequestedParameters.ClientHandle, filter, filter, range, samplingInterval, queueSize,
request.RequestedParameters.DiscardOldest, 0, durable)
{
_owner = owner; _demand = demand; _definition = definition; _nodeId = handle.NodeId;
if (initialSample is not null)
{
_binding = new(initialSample.Proof);
AddCandidate(initialSample, _binding);
}
}
internal NodeId ProjectedNodeId => _nodeId;
internal bool ObserveSample(ProjectedValueWrite sample)
{
lock (_bindingSync)
{
var original = _binding;
var sameSource = original is not null && ReferenceEquals(original.Proof?.SourceIdentity, sample.Proof.SourceIdentity);
if (!sameSource || (_needsSnapshot && sample.IsCompleteSnapshot))
{
original?.Retire();
_binding = null;
if (Volatile.Read(ref _retired) != 0 || !sample.IsCompleteSnapshot || !sample.Proof.IsSourceValid || _demand?.IsValid != true)
{ _needsSnapshot = true; return true; }
// Pinned SDK resets the entire data queue and last value across this transition.
var mode = MonitoringMode;
if (mode != MonitoringMode.Disabled)
{
SetMonitoringMode(MonitoringMode.Disabled);
SetMonitoringMode(mode);
}
ClearCandidates(); _needsSnapshot = false;
Interlocked.Exchange(ref _snapshotRequested, 0);
_binding = new(sample.Proof);
}
if (_binding is null) { _needsSnapshot = true; return true; }
if (_candidates.Any(candidate => ReferenceEquals(candidate.Sample, sample))) return false;
return !AddCandidate(sample, _binding);
}
}
private bool AddCandidate(ProjectedValueWrite sample, SourceBinding binding)
{
long bytes = 256;
if (sample.Snapshot.Value is string text) bytes += 2L * text.Length;
else if (sample.Snapshot.Value is Array array)
{
if (array.Rank != 1 || array.Length > 65_536) { _needsSnapshot = true; return false; }
bytes += 64L * array.Length;
if (array is string[] strings) foreach (var item in strings) bytes += 2L * (item?.Length ?? 0);
}
if (bytes > MaxCandidateBytes || _candidates.Count >= MaxCandidates || _candidateBytes > MaxCandidateBytes - bytes)
{ _needsSnapshot = true; return false; }
if (!_owner.ProjectedCandidateBudget.TryReserve(bytes, out var charge) || charge is null)
{ _needsSnapshot = true; return false; }
try
{
var value = SdkValueBoundary.FromClr(sample.Snapshot.Value,
_definition?.Metadata.ValueKind == DataValueKind.Array && _definition.Metadata.ArrayElementKind == DataValueKind.UInt8);
_candidates.Add(new(sample, value, binding, bytes, charge));
_candidateBytes += bytes;
return true;
}
catch (ArgumentException) { charge.Dispose(); _needsSnapshot = true; return false; }
}
private void ClearCandidates()
{
foreach (var candidate in _candidates) candidate.Charge.Dispose();
_candidates.Clear(); _candidateBytes = 0;
}
internal void RequestBaseline()
{
if (Volatile.Read(ref _retired) != 0 || _demand?.IsValid != true || Interlocked.CompareExchange(ref _snapshotRequested, 1, 0) != 0) return;
if (_demand is not { } demand || !_owner.RequestProjectedSnapshot(demand)) Interlocked.Exchange(ref _snapshotRequested, 0);
}
private bool IsCurrentCandidate(SourceBinding? binding, SampleEvidence? candidate)
{
if (candidate is null || !ReferenceEquals(candidate.Binding, binding) || !IsCurrentBinding(binding) ||
_demand is not { } demand || demand.MaximumSampleAge <= TimeSpan.Zero) return false;
if (candidate.Proof is not { IsValid: true } proof) { RequestBaseline(); return false; }
try
{
var age = candidate.Age.Advance(proof.Clock.GetElapsedTime(candidate.ReceivedTimestamp, proof.Clock.GetTimestamp()));
if (age.IsFresh(demand.MaximumSampleAge)) return proof.IsValid && IsCurrentBinding(binding);
}
catch (Exception ex) when (ex is ArgumentException or OverflowException) { }
RequestBaseline();
return false;
}
private bool IsCurrentBinding(SourceBinding? binding) => Volatile.Read(ref _retired) == 0 && _demand is { IsValid: true } &&
binding is { IsValid: true } && _definition is { } definition && _owner.IsProjectedDefinitionCurrent(_nodeId, definition);
internal bool IsCurrent => IsCurrentBinding(Volatile.Read(ref _binding));
internal bool HasCurrentDemand => Volatile.Read(ref _retired) == 0 && _demand is { IsValid: true } &&
_definition is { } definition && _owner.IsProjectedDefinitionCurrent(_nodeId, definition);
internal void Retire()
{
Interlocked.Exchange(ref _retired, 1);
lock (_bindingSync) { _binding?.Retire(); _binding = null; ClearCandidates(); }
_definition = null;
if (Interlocked.Exchange(ref _released, 1) == 0) Interlocked.Exchange(ref _demand, null)?.Dispose();
}
public override bool Publish(OperationContext context, Queue<MonitoredItemNotification> notifications,
Queue<DiagnosticInfo> diagnostics, uint maximum, ILogger logger)
{
var captured = Volatile.Read(ref _binding);
var local = new Queue<MonitoredItemNotification>();
var localDiagnostics = new Queue<DiagnosticInfo>();
var more = base.Publish(context, local, localDiagnostics, maximum, logger);
while (local.Count > 0)
{
var notification = local.Dequeue();
SampleEvidence? evidence = null;
lock (_bindingSync)
{
var matching = _candidates.Where(candidate => ReferenceEquals(candidate.Binding, captured) &&
candidate.Value.Equals(notification.Value.WrappedValue) && candidate.Sample.Snapshot.StatusCode == notification.Value.StatusCode.Code).Take(2).ToArray();
if (matching.Length == 1)
{
var matched = matching[0]; _candidates.Remove(matched); _candidateBytes -= matched.Bytes;
evidence = matched.Binding.Capture(matched.Sample.Proof, matched.Sample.OriginAgeBounds, matched.Sample.ReceivedTimestamp);
matched.Charge.Dispose();
}
else _needsSnapshot = true;
}
if (evidence is null) RequestBaseline();
var originalSample = evidence;
notification.Message = new ProjectedNotificationMarker(notification.ClientHandle, notification.Value, () => IsCurrentCandidate(captured, originalSample));
notifications.Enqueue(notification);
if (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue());
}
while (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue());
return more;
}
}
@@ -386,3 +607,81 @@ internal sealed class SdkStandbyProjection(OtOpcUaNodeManager nodeManager, WarmS
/// <inheritdoc />
public int RefreshAllEventItems() => nodeManager.RefreshAllEventItems();
}
/// <summary>Captured per-notification proof. A stale pooled helper is treated as denied.</summary>
internal sealed class ProjectedNotificationMarker : NotificationMessage
{
private readonly uint _clientHandle;
private readonly byte[]? _fingerprint;
private readonly Func<bool> _authorize;
public ProjectedNotificationMarker(uint clientHandle, DataValue value, Func<bool> authorize)
{ _clientHandle = clientHandle; _fingerprint = Fingerprint(value); _authorize = authorize; }
public bool Permits(MonitoredItemNotification notification)
{
if (notification.ClientHandle != _clientHandle || _fingerprint is null) return false;
try
{
var current = Fingerprint(notification.Value);
return current is not null && System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(_fingerprint, current) && _authorize();
}
catch { return false; }
}
private static byte[]? Fingerprint(DataValue value)
{
try
{
var payload = SdkValueBoundary.ToClr(value.WrappedValue);
if (payload is Array array)
{
if (array.Rank != 1 || array.Length > 65_536 || array.GetType().GetElementType() is not { } type ||
type != typeof(bool) && type != typeof(sbyte) && type != typeof(byte) && type != typeof(short) && type != typeof(ushort) &&
type != typeof(int) && type != typeof(uint) && type != typeof(long) && type != typeof(ulong) &&
type != typeof(float) && type != typeof(double) && type != typeof(string) && type != typeof(DateTime)) return null;
}
else if (payload is not (null or bool or sbyte or byte or short or ushort or int or uint or long or ulong or float or double or string or DateTime or Guid) ||
payload is string { Length: > 524288 }) return null;
var encoded = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(new
{
Type = payload?.GetType().FullName, Value = payload, Status = value.StatusCode.Code,
Source = value.SourceTimestamp.ToString(), Server = value.ServerTimestamp.ToString()
});
return encoded.Length <= 1024 * 1024 ? System.Security.Cryptography.SHA256.HashData(encoded) : null;
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NotSupportedException or System.Text.Json.JsonException)
{ return null; }
}
}
/// <summary>Rechecks captured projected notification authority for every delivery and retransmission.</summary>
internal static class ProjectedNotificationRewriter
{
public static NotificationMessage Project(NotificationMessage message, bool republish)
{
var changed = false;
var payloads = new List<ExtensionObject>(message.NotificationData.Count);
foreach (var payload in message.NotificationData)
{
if (!payload.TryGetValue<DataChangeNotification>(out var change) || change is null)
{ payloads.Add(payload); continue; }
var items = new List<MonitoredItemNotification>(change.MonitoredItems.Count);
var changedPayload = false;
foreach (var item in change.MonitoredItems)
{
if (item.Message is ProjectedNotificationMarker marker && !marker.Permits(item))
{
items.Add(new MonitoredItemNotification { ClientHandle = item.ClientHandle,
Value = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied, DateTimeUtc.MinValue, item.Value.ServerTimestamp) });
changedPayload = true;
}
else items.Add(item);
}
if (changedPayload)
{
changed = true;
payloads.Add(new ExtensionObject(new DataChangeNotification { MonitoredItems = items, DiagnosticInfos = change.DiagnosticInfos }));
}
else payloads.Add(payload);
}
return changed ? new NotificationMessage { SequenceNumber = message.SequenceNumber, PublishTime = message.PublishTime, NotificationData = payloads } : message;
}
}
@@ -0,0 +1,397 @@
using Akka.Actor;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Owns bounded imported-value messages through the actual SDK apply, with captured route ownership.</summary>
public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDisposable
{
private sealed class Binding(ProjectedValueRoute route)
{
internal ProjectedValueRoute Route { get; } = route;
internal object? SourceIdentity;
internal object? PublicationIdentity;
}
private readonly object _sync = new();
private readonly Dictionary<(DataRealm, string), Binding> _bindings = new();
private readonly HashSet<ProjectedPublicationBatch> _pending = [];
private readonly HashSet<string> _retiredReferences = new(StringComparer.Ordinal);
private readonly Dictionary<string, long> _trackedReferences = new(StringComparer.Ordinal);
private long _controlBytes;
private readonly long _maximumControlBytes;
private IActorRef? _retirementHost;
private bool _retirementWakePending;
private IActorRef? _valueHost;
private bool _valueWakePending;
private IActorRef? _sdkActor;
private bool _sdkWakePending;
private readonly HashSet<ProjectedPublicationBatch> _sdkPending = [];
private IActorRef? _muxTarget;
private ProjectedCoalescingMailbox<ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags.DependencyMuxActor.ProjectedDependency>? _muxMailbox;
private readonly Func<IActorRef?> _host;
private readonly Func<ProjectedValueRoute, bool> _authority;
private readonly int _maximumRoutes;
private readonly long _maximumBytes;
private readonly TimeProvider _clock;
private readonly ITimer _cleanup;
private long _pendingBytes;
private long _nextQueueSequence;
private bool _disposed;
public ActorProjectedValuePublisher(Func<IActorRef?> host, Func<ProjectedValueRoute, bool> authority,
int maximumRoutes, long maximumPendingBytes, TimeProvider clock, long maximumControlBytes = 16 * 1024 * 1024)
{
if (maximumRoutes <= 0 || maximumPendingBytes <= 0 || maximumControlBytes <= 0)
throw new ArgumentOutOfRangeException(nameof(maximumRoutes));
_host = host; _authority = authority; _maximumRoutes = maximumRoutes; _maximumBytes = maximumPendingBytes; _clock = clock;
_maximumControlBytes = maximumControlBytes;
_cleanup = clock.CreateTimer(static state => ((ActorProjectedValuePublisher)state!).SweepQueued(), this,
TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}
public long PendingBytes { get { lock (_sync) return _pendingBytes; } }
public long RetainedControlBytes { get { lock (_sync) return _controlBytes; } }
private static (DataRealm, string) Key(ProjectedValueRoute route) => (route.Realm, route.LocalIdentifier);
private bool Authorized(ProjectedValueRoute route)
{
try
{
route.Serving.Validate(requireEpochs: true);
if (string.IsNullOrWhiteSpace(route.DriverInstanceId) || route.DriverInstanceId.Length > 512 ||
route.Serving.NodeId.Length > 512 || route.Serving.Incarnation.Length > 256 || route.Serving.Role.Length > 32)
return false;
return route.PublicationId != Guid.Empty && route.ProjectionGeneration > 0 && route.Serving.ServingGeneration > 0
&& ProjectedDataIds.TryParseDependencyReference(route.DependencyReference, out var realm, out var id)
&& realm == route.Realm && id == route.LocalIdentifier && _authority(route);
}
catch (Exception) { return false; }
}
public bool TryBind(ProjectedValueRoute route)
{
ArgumentNullException.ThrowIfNull(route);
if (!Authorized(route)) return false;
lock (_sync)
{
if (_disposed) return false;
var bytes = RouteCharge(route);
if (_trackedReferences.TryGetValue(route.DependencyReference, out var held))
{
var additional = Math.Max(0, bytes - held);
if (additional > _maximumControlBytes - _controlBytes) return false;
_trackedReferences[route.DependencyReference] = Math.Max(held, bytes); _controlBytes += additional;
}
else
{
if (_trackedReferences.Count >= _maximumRoutes || bytes > _maximumControlBytes - _controlBytes) return false;
_trackedReferences.Add(route.DependencyReference, bytes); _controlBytes += bytes;
}
if (!_bindings.TryGetValue(Key(route), out var current) || current.Route != route)
_bindings[Key(route)] = new(route);
return true;
}
}
internal static long RouteCharge(ProjectedValueRoute route) => checked(1024L + 8L *
(route.DependencyReference.Length + route.LocalIdentifier.Length + route.DriverInstanceId.Length +
route.Serving.NodeId.Length + route.Serving.Incarnation.Length + route.Serving.Role.Length));
private bool Current(Binding binding)
{
lock (_sync)
if (_disposed || !_bindings.TryGetValue(Key(binding.Route), out var now) || !ReferenceEquals(binding, now)) return false;
return Authorized(binding.Route);
}
private sealed class Witness(ActorProjectedValuePublisher owner, Binding binding,
IProjectedSamplePublicationProof source, object identity, DataAgeBounds ageBounds,
long receivedTimestamp, TimeSpan? maximumAge) : IProjectedSamplePublicationProof
{
public object SourceIdentity => identity;
public bool IsSourceValid { get { try { return owner.Current(binding) && source.IsSourceValid && owner.OwnsIdentity(binding, identity); } catch (Exception) { return false; } } }
public bool IsValid
{
get
{
try
{
if (!IsSourceValid || !source.IsValid) return false;
if (maximumAge is not { } limit) return owner.OwnsIdentity(binding, identity);
var elapsed = Clock.GetElapsedTime(receivedTimestamp);
return limit > TimeSpan.Zero && elapsed >= TimeSpan.Zero && ageBounds.Advance(elapsed).IsFresh(limit) && owner.OwnsIdentity(binding, identity);
}
catch (Exception) { return false; }
}
}
public TimeProvider Clock => source.Clock;
public void Invalidate() { try { source.Invalidate(); } finally { owner.RetireWitness(binding, identity); } }
}
private bool OwnsIdentity(Binding binding, object identity)
{
lock (_sync) return !_disposed && _bindings.TryGetValue(Key(binding.Route), out var current) &&
ReferenceEquals(current, binding) && ReferenceEquals(binding.PublicationIdentity, identity);
}
private void RetireWitness(Binding binding, object identity)
{
var removed = false;
lock (_sync)
if (OwnsIdentity(binding, identity))
{ _bindings.Remove(Key(binding.Route)); _retiredReferences.Add(binding.Route.DependencyReference); removed = true; }
if (removed) NotifyRetirements();
}
private Witness WitnessFor(Binding binding, ProjectedValueUpdate update)
{
var source = update.SourceProof;
var sourceIdentity = source.SourceIdentity ?? throw new InvalidOperationException("Source identity is required.");
lock (_sync)
{
if (!ReferenceEquals(binding.SourceIdentity, sourceIdentity))
{ binding.SourceIdentity = sourceIdentity; binding.PublicationIdentity = new object(); }
return new(this, binding, source, binding.PublicationIdentity!, update.OriginAgeBounds,
update.ReceivedTimestamp, update.MaximumSampleAge);
}
}
private void Invalidate(IEnumerable<ProjectedValueUpdate> updates)
{
foreach (var update in updates)
{
try { update.SourceProof.Invalidate(); } catch (Exception) { }
Retire(update.Route);
}
}
private IActorRef? Host() { try { return _host(); } catch (Exception) { return null; } }
private void SweepQueued()
{
ProjectedPublicationBatch[] pending;
lock (_sync) { if (_disposed) return; pending = _pending.ToArray(); }
foreach (var batch in pending) if (!batch.IsValid) batch.AbortQueued();
NotifyRetirements();
}
public bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates)
{
ArgumentNullException.ThrowIfNull(updates);
if (updates.Count == 0 || updates.Count > _maximumRoutes) { Invalidate(updates); return false; }
var captured = updates.ToArray();
var bindings = new Binding[captured.Length];
long charge = 256;
try
{
if (captured.Select(update => Key(update.Route)).Distinct().Count() != captured.Length) throw new ArgumentException("Duplicate projected route.");
for (var i = 0; i < captured.Length; i++)
{
var update = captured[i];
update.OriginAgeBounds.Validate();
if (!ReferenceEquals(update.SourceProof.Clock, _clock) || !update.SourceProof.IsValid
|| _clock.GetElapsedTime(update.ReceivedTimestamp) < TimeSpan.Zero || !Authorized(update.Route)) return Refused();
charge = checked(charge + 512 + OwnedDataSample.Estimate(update.Snapshot.Value));
}
var admitted = false;
lock (_sync)
{
if (!_disposed && charge <= _maximumBytes - _pendingBytes)
{
admitted = true;
for (var i = 0; i < captured.Length; i++)
if (!_bindings.TryGetValue(Key(captured[i].Route), out bindings[i]!) || bindings[i].Route != captured[i].Route)
{ admitted = false; break; }
if (admitted) _pendingBytes += charge;
}
}
if (!admitted) return Refused();
}
catch (Exception error) when (error is ArgumentException or OverflowException) { return Refused(); }
ProjectedPublicationBatch? batch = null;
try
{
var writes = captured.Select((update, i) => new ProjectedValueWrite(update.Route.Realm, update.Route.LocalIdentifier,
update.Route.ProjectionGeneration, update.Route.Serving,
update.Snapshot with { Value = OwnedDataSample.CopyLegacy(update.Snapshot.Value) }, update.OriginAgeBounds,
update.ReceivedTimestamp, WitnessFor(bindings[i], update), update.IsCompleteSnapshot)).ToArray();
batch = new(writes, captured.Select(update => update.Route).ToArray(), Complete, ForwardToMux);
lock (_sync)
{
// Enqueue is the publication order boundary. Completed slots may be reused in
// ownership sets; their enumeration order never determines sample order.
batch.QueueSequence = checked(++_nextQueueSequence);
_pending.Add(batch);
}
if (!batch.IsValid || Host() is not { } host) { batch.AbortQueued(); return false; }
NotifyValues(host);
return true;
}
catch (Exception)
{
if (batch is not null) batch.AbortQueued();
else { lock (_sync) _pendingBytes -= charge; Invalidate(captured); }
return false;
}
bool Refused() { Invalidate(captured); return false; }
void Complete(ProjectedPublicationBatch completed)
{ lock (_sync) { _pending.Remove(completed); _sdkPending.Remove(completed); _pendingBytes -= charge; } }
}
private void NotifyValues(IActorRef host)
{
lock (_sync)
{
if (_pending.Count == 0 || _valueWakePending && Equals(host, _valueHost)) return;
_valueHost = host; _valueWakePending = true;
}
host.Tell(new DriverHostActor.DrainProjectedValues(this));
}
internal ProjectedPublicationBatch[] TakeQueuedValues(IActorRef host)
{
lock (_sync)
{
if (!Equals(host, _valueHost)) return [];
_valueWakePending = false;
return _pending.OrderBy(batch => batch.QueueSequence).Where(batch => batch.TryForward()).ToArray();
}
}
internal void EnqueueForSdk(ProjectedPublicationBatch batch, IActorRef sdk, IActorRef? mux)
{
var wake = false;
lock (_sync)
{
if (!batch.IsQueued) return;
_sdkPending.Add(batch);
if (!_sdkWakePending || !Equals(_sdkActor, sdk)) { _sdkActor = sdk; _sdkWakePending = true; wake = true; }
}
if (wake) sdk.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.DrainProjectedValues(this, mux));
}
internal ProjectedPublicationBatch[] TakeSdkValues(IActorRef sdk)
{
lock (_sync)
{
if (!Equals(_sdkActor, sdk)) return [];
_sdkWakePending = false;
var result = _sdkPending.Where(batch => batch.IsQueued).OrderBy(batch => batch.QueueSequence).ToArray();
_sdkPending.Clear();
return result;
}
}
private bool ForwardToMux(IActorRef mux, IReadOnlyList<ProjectedValueRoute> routes, IReadOnlyList<ProjectedValueWrite> writes)
{
ProjectedCoalescingMailbox<ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags.DependencyMuxActor.ProjectedDependency> mailbox;
lock (_sync)
{
if (_disposed) return false;
if (_muxMailbox is null || !Equals(_muxTarget, mux))
{
_muxMailbox?.Dispose(); _muxTarget = mux;
_muxMailbox = new(mux, queue => new ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags.DependencyMuxActor.DrainProjectedBatch(queue), _maximumBytes, _maximumRoutes);
}
mailbox = _muxMailbox;
}
try
{
var items = routes.Select((route, index) => (route.DependencyReference,
new ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags.DependencyMuxActor.ProjectedDependency(route.PublicationId.ToString("N"), route.DependencyReference, writes[index]),
checked(512L + OwnedDataSample.Estimate(writes[index].Snapshot.Value) + 2L * route.DependencyReference.Length))).ToArray();
return mailbox.TryOffer(items);
}
catch (Exception error) when (error is ArgumentException or OverflowException or IndexOutOfRangeException) { return false; }
}
public void Retire(ProjectedValueRoute route)
{
var removed = false;
lock (_sync)
if (_bindings.TryGetValue(Key(route), out var binding) && binding.Route == route)
{ _bindings.Remove(Key(route)); _retiredReferences.Add(route.DependencyReference); removed = true; }
if (removed) NotifyRetirements();
}
internal bool IsCurrent(ProjectedValueRoute route)
{
lock (_sync)
if (_disposed || !_bindings.TryGetValue(Key(route), out var binding) || binding.Route != route) return false;
return Authorized(route);
}
internal string[] TakeRetiredReferences(IActorRef host)
{
lock (_sync)
{
if (!Equals(host, _retirementHost)) return [];
var references = _retiredReferences.ToArray();
_retiredReferences.Clear(); _retirementWakePending = false;
foreach (var reference in references)
if (ProjectedDataIds.TryParseDependencyReference(reference, out var realm, out var identifier) &&
!_bindings.ContainsKey((realm, identifier)) && _trackedReferences.Remove(reference, out var bytes))
_controlBytes -= bytes;
return references;
}
}
/// <summary>Rearms outstanding retirement after the owning actor starts or restarts.</summary>
public void HostActivated(IActorRef host)
{
lock (_sync) { _retirementHost = host; _retirementWakePending = false; _valueHost = host; _valueWakePending = false; }
NotifyRetirements(host);
NotifyValues(host);
}
private void NotifyRetirements(IActorRef? activated = null)
{
var host = activated ?? Host();
if (host is null) return;
lock (_sync)
{
if (_retiredReferences.Count == 0 || _retirementWakePending && Equals(host, _retirementHost)) return;
_retirementHost = host; _retirementWakePending = true;
}
host.Tell(new DriverHostActor.DrainProjectedRetirements(this));
}
public void Dispose()
{
ProjectedPublicationBatch[] pending;
ProjectedValueRoute[] routes;
lock (_sync)
{
if (_disposed) return;
_disposed = true; routes = _bindings.Values.Select(binding => binding.Route).ToArray(); _bindings.Clear();
foreach (var route in routes) _retiredReferences.Add(route.DependencyReference);
pending = _pending.ToArray();
}
_cleanup.Dispose();
_muxMailbox?.Dispose();
foreach (var batch in pending) batch.AbortQueued();
NotifyRetirements();
}
}
/// <summary>Queued ownership may abort; physical sink ownership remains charged until completion.</summary>
internal sealed class ProjectedPublicationBatch
{
internal long QueueSequence { get; set; }
private int _state;
private int _forwarded;
private IReadOnlyList<ProjectedValueWrite> _writes;
private IReadOnlyList<ProjectedValueRoute> _routes;
private readonly Action<ProjectedPublicationBatch> _release;
private readonly Func<IActorRef, IReadOnlyList<ProjectedValueRoute>, IReadOnlyList<ProjectedValueWrite>, bool> _forward;
internal ProjectedPublicationBatch(IReadOnlyList<ProjectedValueWrite> writes,
IReadOnlyList<ProjectedValueRoute> routes, Action<ProjectedPublicationBatch> release,
Func<IActorRef, IReadOnlyList<ProjectedValueRoute>, IReadOnlyList<ProjectedValueWrite>, bool> forward)
{ _writes = writes; _routes = routes; _release = release; _forward = forward; }
internal bool ForwardToMux(IActorRef mux) => _forward(mux, Routes, Writes);
internal IReadOnlyList<ProjectedValueWrite> Writes => Volatile.Read(ref _writes);
internal IReadOnlyList<ProjectedValueRoute> Routes => Volatile.Read(ref _routes);
internal bool IsQueued => Volatile.Read(ref _state) == 0;
internal bool TryForward() => IsQueued && Interlocked.Exchange(ref _forwarded, 1) == 0;
internal bool IsValid => Volatile.Read(ref _state) != 2 && Writes.All(value => value.Proof.IsValid);
internal bool TryBegin() => Interlocked.CompareExchange(ref _state, 1, 0) == 0;
internal void AbortQueued()
{
if (Interlocked.CompareExchange(ref _state, 2, 0) != 0) return;
var writes = Interlocked.Exchange(ref _writes, Array.Empty<ProjectedValueWrite>());
Interlocked.Exchange(ref _routes, Array.Empty<ProjectedValueRoute>());
Invalidate(writes); _release(this);
}
internal void Complete(bool success)
{
if (Interlocked.CompareExchange(ref _state, 2, 1) != 1) return;
var writes = Interlocked.Exchange(ref _writes, Array.Empty<ProjectedValueWrite>());
Interlocked.Exchange(ref _routes, Array.Empty<ProjectedValueRoute>());
if (!success) Invalidate(writes);
_release(this);
}
private static void Invalidate(IEnumerable<ProjectedValueWrite> writes) { foreach (var value in writes) try { value.Proof.Invalidate(); } catch (Exception) { } }
}
@@ -0,0 +1,119 @@
using System.Security.Cryptography;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>All authority and topology facts that scope one remote browse continuation.</summary>
public sealed record BrowseContinuationBinding(string PrincipalId, string ApiKeyId, string CredentialVersion,
string MappingId, long MappingRevision, DataView Parent, string? Filter, long LocalCatalogEpoch, ServingIdentity RemoteServing,
DateTimeOffset? CredentialExpiresUtc = null);
/// <summary>Bounded, opaque and single-commit peer cursors. Aborting a reservation preserves its cursor.</summary>
public sealed class BrowseContinuationRegistry
{
private sealed class Entry(BrowseContinuationBinding binding, string cursor, long started, TimeSpan lifetime)
{
internal readonly BrowseContinuationBinding Binding = binding;
internal readonly string Cursor = cursor;
internal readonly long Started = started;
internal readonly TimeSpan Lifetime = lifetime;
internal bool Reserved;
}
private readonly object _sync = new();
private readonly Dictionary<string, Entry> _entries = new(StringComparer.Ordinal);
private readonly int _maximum;
private readonly TimeProvider _clock;
public BrowseContinuationRegistry(int maximum, TimeProvider clock)
{
if (maximum <= 0) throw new ArgumentOutOfRangeException(nameof(maximum));
_maximum = maximum; _clock = clock ?? throw new ArgumentNullException(nameof(clock));
}
public string Issue(BrowseContinuationBinding binding, string peerCursor, TimeSpan lifetime, long? requestStartedTimestamp = null)
{
ArgumentNullException.ThrowIfNull(binding); ArgumentException.ThrowIfNullOrWhiteSpace(peerCursor);
if (peerCursor.Length > 4096 || lifetime <= TimeSpan.Zero || lifetime > TimeSpan.FromSeconds(60)) throw new ArgumentOutOfRangeException(nameof(lifetime));
binding.Parent.Validate(); binding.RemoteServing.Validate(true);
if (binding.MappingRevision <= 0 || binding.LocalCatalogEpoch <= 0 || string.IsNullOrWhiteSpace(binding.PrincipalId) ||
string.IsNullOrWhiteSpace(binding.ApiKeyId) || string.IsNullOrWhiteSpace(binding.CredentialVersion) || string.IsNullOrWhiteSpace(binding.MappingId))
throw new ArgumentException("Invalid continuation binding.", nameof(binding));
lock (_sync)
{
Sweep();
if (_entries.Count >= _maximum) throw new InvalidOperationException("Continuation capacity exhausted.");
var entry = new Entry(binding, peerCursor, requestStartedTimestamp ?? _clock.GetTimestamp(), lifetime);
if (Expired(entry)) throw new InvalidOperationException("Continuation lifetime has already elapsed.");
var token = NewToken(); _entries.Add(token, entry); return token;
}
}
public bool TryPrepare(string token, BrowseContinuationBinding binding, out PreparedBrowseContinuation? prepared)
{
prepared = null;
if (string.IsNullOrWhiteSpace(token) || token.Length != 64) return false;
lock (_sync)
{
Sweep();
if (!_entries.TryGetValue(token, out var entry) || entry.Reserved || entry.Binding != binding) return false;
entry.Reserved = true; prepared = new(this, token, entry.Cursor); return true;
}
}
private void Sweep()
{
foreach (var pair in _entries.Where(pair => Expired(pair.Value)).ToArray()) _entries.Remove(pair.Key);
}
private bool Expired(Entry entry)
{
var age = _clock.GetElapsedTime(entry.Started, _clock.GetTimestamp());
return age < TimeSpan.Zero || age >= entry.Lifetime ||
entry.Binding.CredentialExpiresUtc is { } expiry && expiry <= _clock.GetUtcNow();
}
private string NewToken()
{
string token;
do { token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); } while (_entries.ContainsKey(token));
return token;
}
internal bool Commit(string token, string? nextCursor, out string? nextToken)
{
nextToken = null;
lock (_sync)
{
if (!_entries.TryGetValue(token, out var entry) || !entry.Reserved || Expired(entry)) { _entries.Remove(token); return false; }
if (nextCursor is { Length: > 4096 } || nextCursor is { Length: 0 }) return false;
_entries.Remove(token);
if (nextCursor is not null)
{
nextToken = NewToken();
_entries.Add(nextToken, new(entry.Binding, nextCursor, entry.Started, entry.Lifetime));
}
return true;
}
}
internal void Abort(string token)
{
lock (_sync) if (_entries.TryGetValue(token, out var entry)) { if (Expired(entry)) _entries.Remove(token); else entry.Reserved = false; }
}
public void InvalidateMapping(string mappingId)
{
lock (_sync) foreach (var pair in _entries.Where(pair => string.Equals(pair.Value.Binding.MappingId, mappingId, StringComparison.OrdinalIgnoreCase)).ToArray()) _entries.Remove(pair.Key);
}
}
/// <summary>A cursor reservation, committed only after the corresponding page is published.</summary>
public sealed class PreparedBrowseContinuation : IDisposable
{
private readonly BrowseContinuationRegistry _owner;
private readonly string _token;
private int _finished;
internal PreparedBrowseContinuation(BrowseContinuationRegistry owner, string token, string remoteCursor)
{ _owner = owner; _token = token; RemoteCursor = remoteCursor; }
public string RemoteCursor { get; }
public bool TryCommit(string? nextPeerCursor, out string? nextToken)
{
nextToken = null;
if (Interlocked.Exchange(ref _finished, 1) != 0) return false;
var committed = _owner.Commit(_token, nextPeerCursor, out nextToken);
if (!committed) _owner.Abort(_token);
return committed;
}
public void Dispose() { if (Interlocked.Exchange(ref _finished, 1) == 0) _owner.Abort(_token); }
}
@@ -0,0 +1,139 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Retained, deployment-authorized configured projection acquisition.</summary>
public interface IConfiguredProjectionLease : IAsyncDisposable { bool IsValid { get; } }
/// <summary>Discovers a configured projection from current deployed scope and verified origin pages.</summary>
public interface IConfiguredProjectionDiscovery { Task<IConfiguredProjectionLease?> ResolveAsync(string reference, CancellationToken cancellationToken); }
/// <summary>Bounded aggregate interests driven by a fixed worker pool and one shared retry sweep.</summary>
public sealed class ConfiguredProjectedInterestOwner : IProjectedDependencyInterestSink, IAsyncDisposable
{
private sealed class Entry(string reference, long bytes)
{
internal readonly string Reference = reference;
internal readonly long Bytes = bytes;
internal bool Desired = true, Queued, Running;
internal IConfiguredProjectionLease? Lease;
internal CancellationTokenSource? InFlight;
}
private readonly object _sync = new();
private readonly Dictionary<string, Entry> _entries = new(StringComparer.Ordinal);
private readonly Queue<Entry> _ready = new();
private readonly SemaphoreSlim _available = new(0);
private readonly CancellationTokenSource _stop = new();
private readonly IConfiguredProjectionDiscovery _discovery;
private readonly int _maxInterests;
private readonly long _maxBytes;
private readonly TimeProvider _clock;
private readonly Task[] _workers;
private readonly Task _sweep;
private long _bytes;
private bool _disposed;
public ConfiguredProjectedInterestOwner(IConfiguredProjectionDiscovery discovery, int maxInterests,
int maxConcurrentCalls = 4, long maxTransportBytes = 16 * 1024 * 1024, TimeProvider? clock = null)
{
_discovery = discovery ?? throw new ArgumentNullException(nameof(discovery));
if (maxInterests <= 0 || maxConcurrentCalls <= 0 || maxTransportBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxInterests));
_maxInterests = maxInterests; _maxBytes = maxTransportBytes; _clock = clock ?? TimeProvider.System;
_workers = Enumerable.Range(0, maxConcurrentCalls).Select(_ => Task.Run(WorkAsync)).ToArray();
_sweep = Task.Run(SweepAsync);
}
private void Queue(Entry entry)
{
if (entry.Queued || entry.Running) return;
entry.Queued = true; _ready.Enqueue(entry); _available.Release();
}
public void SetInterest(string projectedReference, bool active)
{
if (!ProjectedDataIds.TryParseDependencyReference(projectedReference, out _, out _)) return;
lock (_sync)
{
if (_disposed) return;
if (_entries.TryGetValue(projectedReference, out var old))
{
if (old.Desired == active) return;
old.Desired = active; if (!active && old.InFlight is { } stop) _ = stop.CancelAsync();
Queue(old); return;
}
var bytes = checked(256L + 2L * projectedReference.Length);
if (!active || _entries.Count >= _maxInterests || bytes > _maxBytes - _bytes) return;
var entry = new Entry(projectedReference, bytes); _entries.Add(projectedReference, entry); _bytes += bytes; Queue(entry);
}
}
private async Task WorkAsync()
{
while (true)
{
await _available.WaitAsync().ConfigureAwait(false);
Entry? entry;
lock (_sync)
{
if (_ready.Count == 0) { if (_disposed) return; continue; }
entry = _ready.Dequeue(); entry.Queued = false; entry.Running = true;
}
IConfiguredProjectionLease? old;
bool desired;
lock (_sync) { desired = !_disposed && entry.Desired; old = entry.Lease; entry.Lease = null; }
var oldValid = false;
try { oldValid = old is not null && old.IsValid; } catch (Exception) { }
if (old is not null && desired && oldValid)
{
lock (_sync) { entry.Lease = old; entry.Running = false; if (!entry.Desired || _disposed) Queue(entry); }
continue;
}
if (old is not null) { try { await old.DisposeAsync().ConfigureAwait(false); } catch (Exception) { } }
CancellationTokenSource? operation = null;
lock (_sync)
{
desired = !_disposed && entry.Desired;
if (desired) { operation = new CancellationTokenSource(); entry.InFlight = operation; }
}
IConfiguredProjectionLease? acquired = null;
var canceled = false;
if (operation is not null)
{
try { acquired = await _discovery.ResolveAsync(entry.Reference, operation.Token).ConfigureAwait(false); }
catch (Exception) { }
lock (_sync) entry.InFlight = null;
canceled = operation.IsCancellationRequested; operation.Dispose();
}
bool retain;
try { retain = !canceled && acquired is { IsValid: true }; } catch (Exception) { retain = false; }
lock (_sync) retain = retain && !_disposed && entry.Desired;
if (!retain && acquired is not null) { try { await acquired.DisposeAsync().ConfigureAwait(false); } catch (Exception) { } acquired = null; }
lock (_sync)
{
entry.Lease = acquired; entry.Running = false;
if (!entry.Desired || _disposed)
{
if (entry.Lease is not null) Queue(entry);
else { _entries.Remove(entry.Reference); _bytes -= entry.Bytes; if (_disposed && _entries.Count == 0) for (var i = 0; i < _workers.Length; i++) _available.Release(); }
}
}
}
}
private async Task SweepAsync()
{
try
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1), _clock);
while (await timer.WaitForNextTickAsync(_stop.Token).ConfigureAwait(false))
lock (_sync) foreach (var entry in _entries.Values) if (entry.Desired) Queue(entry);
}
catch (OperationCanceledException) { }
}
public async ValueTask DisposeAsync()
{
lock (_sync)
{
if (_disposed) return;
_disposed = true; _stop.Cancel();
foreach (var entry in _entries.Values) { entry.Desired = false; if (entry.InFlight is { } operation) _ = operation.CancelAsync(); Queue(entry); }
if (_entries.Count == 0) for (var i = 0; i < _workers.Length; i++) _available.Release();
}
await _sweep.ConfigureAwait(false); await Task.WhenAll(_workers).ConfigureAwait(false);
_stop.Dispose(); _available.Dispose();
}
}
@@ -0,0 +1,22 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Internal deployment-scoped authority; never accepted from an SDK caller.</summary>
internal sealed class ConfiguredProjectionCapability(string mappingId, long revision, DataRealm realm, DataOperations operations,
IDataMappedCatalogAuthority sourceAuthority, Func<bool> current)
{
internal string Nonce { get; } = Guid.NewGuid().ToString("N");
internal bool Matches(string mapping, DataView view, IDataMappedCatalogAuthority? authority)
{
try
{
return current() && sourceAuthority.IsActive && (operations & (DataOperations.Browse | DataOperations.Subscribe)) == (DataOperations.Browse | DataOperations.Subscribe) &&
string.Equals(mapping, mappingId, StringComparison.OrdinalIgnoreCase) &&
string.Equals(view.MappingId, mapping, StringComparison.OrdinalIgnoreCase) && view.MappingRevision == revision &&
view.Realm == realm && (authority is null || ReferenceEquals(authority, sourceAuthority));
}
catch (Exception) { return false; }
}
}
@@ -0,0 +1,93 @@
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Discovers configured dependencies by walking only committed, placement-scoped origin pages.</summary>
public sealed class ConfiguredProjectionDiscovery : IConfiguredProjectionDiscovery
{
private readonly ProjectedMappingDeploymentRuntime _placements;
private readonly IFederatedProjectionCatalog _catalog;
private readonly ProjectedNamespaceApplier _applier;
private readonly IProjectedNodeLookup _nodes;
private readonly ProjectedDataAccess _access;
private readonly DataBudget _budget;
private readonly int _maxPages;
public ConfiguredProjectionDiscovery(ProjectedMappingDeploymentRuntime placements, IFederatedProjectionCatalog catalog,
ProjectedNamespaceApplier applier, IProjectedNodeLookup nodes, ProjectedDataAccess access, DataBudget budget, int maxPages)
{
_placements = placements ?? throw new ArgumentNullException(nameof(placements)); _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
_applier = applier ?? throw new ArgumentNullException(nameof(applier)); _nodes = nodes ?? throw new ArgumentNullException(nameof(nodes));
_access = access ?? throw new ArgumentNullException(nameof(access)); _budget = budget ?? throw new ArgumentNullException(nameof(budget));
budget.Validate(); if (maxPages <= 0) throw new ArgumentOutOfRangeException(nameof(maxPages)); _maxPages = maxPages;
}
public async Task<IConfiguredProjectionLease?> ResolveAsync(string reference, CancellationToken cancellationToken)
{
if (!ProjectedDataIds.TryParseDependencyReference(reference, out var realm, out var identifier) ||
!ProjectedDataIds.TryDecodeIdentifier(identifier, out var mappingId, out var target) || target is null) return null;
if (!_placements.TryAcquireConfiguredCapability(mappingId, realm, out var capability, out var placement) || capability is null || placement is null ||
target.NamespaceUri != placement.Mapping.RemoteNamespaceUri ||
!string.Equals(target.OriginClusterId, placement.Anchor.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase) ||
!capability.Matches(mappingId, placement.Anchor, placement.Authority)) return null;
if (_catalog.TryResolveProjected(realm, identifier, out var existing) && existing is not null &&
existing.OriginMetadata.View.Address == target && capability.Matches(mappingId, existing.Metadata.View, existing.Resolver.LocalAuthority) &&
_nodes.TryGetNodeId(ProjectedDataIds.NamespaceUri(realm), identifier, out var existingNode) && existingNode is { } readyNode &&
_access.TryAcquireConfigured(readyNode, capability, out var readyDemand) && readyDemand is not null)
{
if (_access.StartSubscription(readyDemand, TimeSpan.FromMilliseconds(placement.Mapping.PublishingIntervalMilliseconds)))
return new Lease(_access, readyDemand, capability, existing);
readyDemand.Dispose();
}
var anchorId = ProjectedDataIds.Identifier(mappingId, placement.Anchor.Address);
if (!_nodes.TryGetNodeId(ProjectedDataIds.NamespaceUri(realm), anchorId, out var anchor) || anchor is not { } anchorNode) return null;
var started = _catalog.Clock.GetTimestamp();
var queue = new Queue<(DataView View, NodeId Node, int Depth)>(); queue.Enqueue((placement.Anchor, anchorNode, 0));
var visited = new HashSet<DataAddress> { placement.Anchor.Address }; var pages = 0; var nodes = 0;
while (queue.TryDequeue(out var current))
{
string? cursor = null;
do
{
cancellationToken.ThrowIfCancellationRequested();
if (++pages > _maxPages || !capability.Matches(mappingId, placement.Anchor, placement.Authority)) return null;
var request = new ProjectedBrowseRequest(mappingId, current.View, null, cursor, null!, _budget, started) { ConfiguredCapability = capability };
if (await _applier.ApplyPageResultAsync(request, current.Node, cancellationToken).ConfigureAwait(false) != ProjectionPageStatus.Ready) return null;
var page = _catalog.TryGetParent(request);
if (page.Status != ProjectionPageStatus.Ready || page.Lease is not { IsValid: true } || !capability.Matches(mappingId, placement.Anchor, placement.Authority)) return null;
if (page.ParentProof is { } rootProof && ProjectedCatalogCache.IsValueNode(rootProof.Metadata) &&
rootProof.OriginMetadata.View.Address == target && capability.Matches(mappingId, rootProof.Metadata.View, rootProof.Resolver.LocalAuthority) &&
_catalog.TryResolveProjected(realm, rootProof.LocalIdentifier, out var indexedRoot) && indexedRoot is not null &&
_nodes.TryGetNodeId(ProjectedDataIds.NamespaceUri(realm), rootProof.LocalIdentifier, out var rootNode) && rootNode is { } actualRoot &&
_access.TryAcquireConfigured(actualRoot, capability, out var rootDemand) && rootDemand is not null)
{
if (_access.StartSubscription(rootDemand, TimeSpan.FromMilliseconds(placement.Mapping.PublishingIntervalMilliseconds)))
return new Lease(_access, rootDemand, capability, indexedRoot);
rootDemand.Dispose(); return null;
}
foreach (var proof in page.Items)
{
if (++nodes > placement.Mapping.MaxProjectionNodes || !capability.Matches(mappingId, proof.Metadata.View, proof.Resolver.LocalAuthority)) return null;
if (!_nodes.TryGetNodeId(ProjectedDataIds.NamespaceUri(realm), proof.LocalIdentifier, out var node) || node is not { } child) return null;
if (proof.OriginMetadata.View.Address == target)
{
if (!_access.TryAcquireConfigured(child, capability, out var demand) || demand is null) return null;
if (!_access.StartSubscription(demand, TimeSpan.FromMilliseconds(placement.Mapping.PublishingIntervalMilliseconds))) { demand.Dispose(); return null; }
return new Lease(_access, demand, capability, proof);
}
if (current.Depth + 1 < placement.Mapping.MaxProjectionDepth && visited.Add(proof.OriginMetadata.View.Address))
queue.Enqueue((proof.Metadata.View, child, current.Depth + 1));
}
cursor = page.Continuation;
if (page.Complete != (cursor is null)) return null;
} while (cursor is not null);
}
return null;
}
private sealed class Lease(ProjectedDataAccess access, IProjectedDemandLease demand, ConfiguredProjectionCapability capability, ProjectedNodeProof proof) : IConfiguredProjectionLease
{
private int _disposed;
public bool IsValid => Volatile.Read(ref _disposed) == 0 && demand.IsValid && capability.Matches(proof.Metadata.View.MappingId!, proof.Metadata.View, proof.Resolver.LocalAuthority);
public ValueTask DisposeAsync() => Interlocked.Exchange(ref _disposed, 1) == 0 ? access.DisposeConfiguredAsync(demand) : ValueTask.CompletedTask;
}
}
@@ -467,10 +467,17 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDisposable
public async Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
{
Check(DataOperations.Subscribe); var stream = await _inner.SubscribeAsync(cancellationToken).ConfigureAwait(false);
try { Check(DataOperations.Subscribe); return new ScopedSubscription(this, stream); }
try { Check(DataOperations.Subscribe); return stream is IDataSubscriptionProvenance provenance
? new ProvenancedScopedSubscription(this, stream, provenance.Serving)
: new ScopedSubscription(this, stream); }
catch { await stream.DisposeAsync().ConfigureAwait(false); throw; }
}
private sealed class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription
private sealed class ProvenancedScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner, ServingIdentity serving)
: ScopedSubscription(owner, inner), IDataSubscriptionProvenance
{
public ServingIdentity Serving { get; } = serving;
}
private class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription
{
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
@@ -72,7 +72,8 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func<L
if (!string.Equals(current.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)
|| !node.SourceEnabled || !node.Supported || !node.Metadata.Writable
|| !ValueMatches(node.Metadata, item.Value) || item.ExpectedCatalogRevision != current.Serving.CatalogEpoch
|| item.ExpectedServingIncarnation != current.Serving.Incarnation)
|| item.ExpectedServingIncarnation != current.Serving.Incarnation
|| item.ExpectedServingGeneration is { } generation && (generation <= 0 || generation != current.Serving.ServingGeneration))
return Reject("Write unavailable before dispatch.");
if (string.IsNullOrWhiteSpace(item.OperationId) || string.IsNullOrWhiteSpace(item.CorrelationId))
return Reject("Invalid write identity.");
@@ -82,8 +83,10 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func<L
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
{ return Reject("Invalid write value."); }
var result = registry.Claim(context.PrincipalId, item.OperationId, item.ExpectedServingIncarnation, hash);
if (result.Kind is WriteClaimKind.Conflict or WriteClaimKind.Stale or WriteClaimKind.Capacity || result.Claim is null)
return Reject("Write operation conflict or capacity exhausted.");
if (result.Kind is WriteClaimKind.Conflict or WriteClaimKind.Stale)
return new(item.CorrelationId, Unknown);
if (result.Kind == WriteClaimKind.Capacity || result.Claim is null)
return Reject("Write operation capacity exhausted.");
var claim = result.Claim;
if (result.Kind == WriteClaimKind.Existing)
{
@@ -185,6 +188,8 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func<L
DataFingerprintEncoding.AppendString(hash, canonicalView.Subject);
DataFingerprintEncoding.AppendInt64(hash, item.ExpectedCatalogRevision);
DataFingerprintEncoding.AppendString(hash, item.ExpectedServingIncarnation);
DataFingerprintEncoding.AppendByte(hash, item.ExpectedServingGeneration.HasValue ? (byte)1 : (byte)0);
if (item.ExpectedServingGeneration is { } generation) DataFingerprintEncoding.AppendInt64(hash, generation);
item.Value.AppendSemanticFingerprint(hash);
return hash.GetHashAndReset();
}
@@ -0,0 +1,25 @@
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Uses the actual deployed, role-guarded connection registry for projection work.</summary>
public sealed class DeployedGrpcDataConnectionSource(DataConnectionDeploymentRuntime runtime) : IGrpcDataAdapterConnectionSource
{
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (!runtime.TryAcquire(connectionId, out var lease) || lease is null)
return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null);
if (cancellationToken.IsCancellationRequested)
{
lease.Dispose();
cancellationToken.ThrowIfCancellationRequested();
}
return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Borrowed(lease));
}
private sealed class Borrowed(DataConnectionDeploymentLease lease) : IGrpcDataAdapterConnectionLease
{
public Core.Abstractions.DataConnections.IDataConnection Connection => lease.Connection;
public CancellationToken CancellationToken => lease.CancellationToken;
public ValueTask DisposeAsync() => lease.DisposeAsync();
}
}
@@ -0,0 +1,104 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Combines the remote metadata lease with local catalog and connection retirement fences.</summary>
internal sealed class BoundProjectionLease(MetadataAuthorityLease remote, CancellationToken route,
IDataMappedCatalogAuthority local, ProjectedCatalogCache cache, string mapping, long generation, Func<bool> bindingCurrent) : IDataAuthorizationLease
{
public ServingIdentity Serving => remote.Serving;
public bool IsValid => !route.IsCancellationRequested && local.IsActive && remote.IsValid && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation);
}
/// <summary>A page holds its physical connection lease until the caller commits or aborts it.</summary>
internal sealed class PreparedPage : IProjectedPreparedPage
{
private readonly ProjectedCatalogCache? _cache;
private readonly BrowseContinuationRegistry? _cursors;
private readonly ProjectedBrowseRequest? _request;
private readonly BrowseContinuationBinding? _binding;
private readonly PreparedBrowseContinuation? _cursor;
private readonly string? _nextPeerCursor;
private readonly SharedPageConnection? _connection;
private readonly TimeProvider? _clock;
private readonly TimeSpan _cursorLifetime;
private readonly long _cursorStart;
private readonly int _maximumMappingNodes;
private int _finished;
private ProjectedParentSnapshot _snapshot;
private PreparedPage(ProjectionPageStatus status) => _snapshot = new(status, [], false, null, 0);
internal PreparedPage(ProjectedCatalogCache cache, BrowseContinuationRegistry cursors, ProjectedBrowseRequest request,
ProjectedParentSnapshot snapshot, BrowseContinuationBinding binding, PreparedBrowseContinuation? cursor, string? nextPeerCursor,
IGrpcDataAdapterConnectionLease connection, SemaphoreSlim slots, TimeProvider clock, TimeSpan cursorLifetime, int maximumMappingNodes)
{
_cache = cache; _cursors = cursors; _request = request; _snapshot = snapshot; _binding = binding;
_cursor = cursor; _nextPeerCursor = nextPeerCursor; _connection = new SharedPageConnection(connection, slots); _clock = clock;
_cursorLifetime = cursorLifetime; _cursorStart = request.RequestStartedTimestamp; _maximumMappingNodes = maximumMappingNodes;
}
private PreparedPage(PreparedPage original, ProjectedBrowseRequest request)
{
_cache = original._cache; _cursors = original._cursors; _request = request; _snapshot = original._snapshot; _binding = original._binding;
_nextPeerCursor = original._nextPeerCursor; _connection = original._connection; _connection!.AddReference();
_clock = original._clock; _cursorLifetime = original._cursorLifetime; _cursorStart = original._cursorStart; _maximumMappingNodes = original._maximumMappingNodes;
}
internal static PreparedPage Failed(ProjectionPageStatus status) => new(status);
internal PreparedPage CloneForWaiter(ProjectedBrowseRequest request) => _connection is null
? Failed(_snapshot.Status) : new PreparedPage(this, request);
public ProjectedParentSnapshot Snapshot => _snapshot;
public bool TryCommit()
{
if (Interlocked.Exchange(ref _finished, 1) != 0 || _cache is null || _request is null || _binding is null || _cursors is null || _clock is null) return false;
try
{
if (_connection!.CancellationToken.IsCancellationRequested || _snapshot.Lease is not { IsValid: true } ||
_clock.GetElapsedTime(_request.RequestStartedTimestamp, _clock.GetTimestamp()) >= _request.Budget.Timeout) return false;
var ok = _cache.TryPublish(_request, _snapshot, () =>
{
if (_cursor is not null) return (_cursor.TryCommit(_nextPeerCursor, out var next), next);
if (_nextPeerCursor is null) return (true, null);
// The lease deadline is measured from the original RPC start, not reply receipt.
var lifetime = _cursorLifetime > TimeSpan.FromSeconds(60) ? TimeSpan.FromSeconds(60) : _cursorLifetime;
return (true, _cursors.Issue(_binding, _nextPeerCursor, lifetime, _cursorStart));
}, out var committed, _maximumMappingNodes);
if (ok) _snapshot = committed!;
return ok;
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
finally { _cursor?.Dispose(); Release(); }
}
public void Dispose()
{
if (Interlocked.Exchange(ref _finished, 1) != 0) return;
_cursor?.Dispose(); Release();
}
private void Release() => _connection?.Release();
internal async Task DisposeAndWaitAsync()
{
Dispose();
if (_connection is not null) await _connection.Closed.ConfigureAwait(false);
}
}
/// <summary>Counts every prepared page that still owns one shared physical connection.</summary>
internal sealed class SharedPageConnection(IGrpcDataAdapterConnectionLease connection, SemaphoreSlim slots)
{
private int _references = 1;
private readonly TaskCompletionSource _closed = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal Task Closed => _closed.Task;
public CancellationToken CancellationToken => connection.CancellationToken;
public void AddReference()
{
if (Interlocked.Increment(ref _references) <= 1) throw new ObjectDisposedException(nameof(SharedPageConnection));
}
public void Release()
{
if (Interlocked.Decrement(ref _references) == 0) _ = CloseAsync();
}
private async Task CloseAsync()
{
try { await connection.DisposeAsync().ConfigureAwait(false); }
catch (Exception) { }
finally { slots.Release(); _closed.TrySetResult(); }
}
}
@@ -225,10 +225,10 @@ public sealed class GrpcDataConnection : IDataConnection
{
var channel = await ChannelAsync(endpoint, ct).ConfigureAwait(false);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, channel.Retired.Token, _shutdown.Token);
var response = await channel.Client.GetCapabilitiesAsync(new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 2 },
var response = await channel.Client.GetCapabilitiesAsync(new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 3 },
Options(channel, start, budget, linked.Token)).ResponseAsync.ConfigureAwait(false);
var caps = DataProtoMapper.DecodeCapabilities(response, new DataDecodeLimits(budget.MaxItems, _maxMessageBytes));
if (!caps.ResponseServingIdentity || caps.Serving.ServingGeneration <= 0 || !ClusterEndpointSelector.IsEligible(Target, caps, write) ||
if (!caps.ResponseServingIdentity || (write && (caps.ProtocolMinor < 3 || !caps.WriteServingGenerationEnforced)) || caps.Serving.ServingGeneration <= 0 || !ClusterEndpointSelector.IsEligible(Target, caps, write) ||
Target.Mode == DataTargetMode.Cluster && !_eligibleNodeIds!.Contains(caps.Serving.NodeId))
throw new InvalidOperationException("Endpoint is not an authenticated ready target.");
linked.Token.ThrowIfCancellationRequested();
@@ -272,8 +272,13 @@ public sealed class GrpcDataConnection : IDataConnection
}
finally { if (admitted) _unaryCapacity.Release(); ExitWork(); }
}
private static bool SupportsWrites(DataCapabilities caps) => caps.ProtocolMinor >= 3 && caps.WriteServingGenerationEnforced;
private static DataMetadata ExposeMetadata(DataMetadata metadata, ServingIdentity serving, DataCapabilities caps) =>
SupportsWrites(caps) ? metadata with { Serving = serving } : metadata with
{ Serving = serving, Writable = false, AllowedOperations = metadata.AllowedOperations & ~DataOperations.Write };
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) =>
QueryAsync(budget, (selected, _, _) => Task.FromResult(selected.Capabilities), cancellationToken);
QueryAsync(budget, (selected, _, _) => Task.FromResult(SupportsWrites(selected.Capabilities) ? selected.Capabilities :
selected.Capabilities with { Operations = selected.Capabilities.Operations & ~DataOperations.Write }), cancellationToken);
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) =>
QueryAsync(request.Budget, async (selected, budget, options) =>
{
@@ -282,9 +287,11 @@ public sealed class GrpcDataConnection : IDataConnection
if (result.Lease is { } lease && (lease.CatalogEpoch != selected.Capabilities.Serving.CatalogEpoch ||
lease.AuthorityEpoch != selected.Capabilities.Serving.AuthorityEpoch || lease.Duration > selected.Capabilities.Limits.MaxMetadataLease))
throw new InvalidOperationException("Browse lease has unexpected authority or duration.");
if (result.Parent != request.Parent || result.Items.Any(x => !string.Equals(x.View.Address.OriginClusterId, selected.Capabilities.ClusterId, StringComparison.OrdinalIgnoreCase)))
if (result.Parent != request.Parent || result.Items.Any(x => x.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch || !string.Equals(x.View.Address.OriginClusterId, selected.Capabilities.ClusterId, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException("Browse response has unexpected provenance.");
Verify(wire.Serving, selected); return result;
Verify(wire.Serving, selected);
var serving = DataProtoMapper.DecodeServing(wire.Serving);
return result with { Serving = serving, Items = result.Items.Select(x => ExposeMetadata(x, serving, selected.Capabilities)).ToArray() };
}, cancellationToken);
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) =>
QueryAsync(request.Budget, async (selected, budget, options) =>
@@ -292,9 +299,11 @@ public sealed class GrpcDataConnection : IDataConnection
var wire = await selected.Channel.Client.GetMetadataAsync(DataProtoMapper.EncodeMetadataRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false);
Verify(wire.Serving, selected); var result = DataProtoMapper.DecodeMetadataResponse(wire, Limits(budget, selected.Capabilities));
if (result.Count != request.Views.Count || result.Where((x, i) => x.CorrelationId != i.ToString(System.Globalization.CultureInfo.InvariantCulture) ||
x.Value is not null && x.Value.View.Address != request.Views[i].Address).Any())
x.Value is not null && (x.Value.View.Address != request.Views[i].Address || x.Value.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch)).Any())
throw new InvalidOperationException("Metadata response has unexpected items.");
Verify(wire.Serving, selected); return result;
Verify(wire.Serving, selected);
var serving = DataProtoMapper.DecodeServing(wire.Serving);
return (IReadOnlyList<DataItemResult<DataMetadata>>)result.Select(x => x.Value is null ? x : x with { Value = ExposeMetadata(x.Value, serving, selected.Capabilities) }).ToArray();
}, cancellationToken);
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken)
{
@@ -353,30 +362,61 @@ public sealed class GrpcDataConnection : IDataConnection
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException)
{ continue; }
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token);
// Caller-bound generations are strict: never replace any supplied precondition or rebind.
var strictMismatch = eligible.Where(i => request.Items[i].ExpectedServingGeneration is { } generation &&
(generation <= 0 || generation != selected.Capabilities.Serving.ServingGeneration ||
request.Items[i].ExpectedCatalogRevision != selected.Capabilities.Serving.CatalogEpoch ||
request.Items[i].ExpectedServingIncarnation != selected.Capabilities.Serving.Incarnation)).ToArray();
foreach (var index in strictMismatch)
results[index] = new(request.Items[index].CorrelationId, new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Serving precondition mismatch."));
eligible = eligible.Except(strictMismatch).ToArray();
if (eligible.Length == 0) { eligible = strictMismatch; continue; }
var items = eligible.Select(i => request.Items[i]).ToArray();
var deferred = strictMismatch.ToList();
if (attempted)
{
// A retry needs fresh, authenticated metadata from the new primary. Never infer a
// catalog revision from its serving epoch or reuse the old node incarnation.
try
// Only legacy retries require fresh metadata. A failed lookup must not suppress
// independently matching, not-yet-dispatched strict items on this endpoint.
var legacy = Enumerable.Range(0, items.Length)
.Where(i => request.Items[eligible[i]].ExpectedServingGeneration is null).ToArray();
var metadataValid = legacy.Length == 0;
if (legacy.Length > 0)
{
var remaining = Remaining(start, request.Budget);
var budget = request.Budget with { Timeout = remaining };
var metadataRequest = new MetadataRequest(items.Select(x => x.View).ToArray(), budget);
var wireMetadata = await selected.Channel.Client.GetMetadataAsync(DataProtoMapper.EncodeMetadataRequest(metadataRequest),
Options(selected.Channel, start, request.Budget, linked.Token)).ResponseAsync.ConfigureAwait(false);
Verify(wireMetadata.Serving, selected);
var metadata = DataProtoMapper.DecodeMetadataResponse(wireMetadata, Limits(budget, selected.Capabilities));
if (metadata.Count != items.Length || metadata.Where((x, i) => x.CorrelationId != i.ToString(System.Globalization.CultureInfo.InvariantCulture) ||
x.Status != DataItemStatus.Good || x.Value is null || x.Value.View.Address != items[i].View.Address ||
!x.Value.Writable || (x.Value.AllowedOperations & DataOperations.Write) == 0).Any()) continue;
linked.Token.ThrowIfCancellationRequested(); Verify(wireMetadata.Serving, selected);
items = items.Select((x, i) => x with { ExpectedCatalogRevision = metadata[i].Value!.CatalogRevision,
ExpectedServingIncarnation = selected.Capabilities.Serving.Incarnation }).ToArray();
try
{
var remaining = Remaining(start, request.Budget);
var budget = request.Budget with { Timeout = remaining };
var metadataRequest = new MetadataRequest(legacy.Select(i => items[i].View).ToArray(), budget);
var wireMetadata = await selected.Channel.Client.GetMetadataAsync(DataProtoMapper.EncodeMetadataRequest(metadataRequest),
Options(selected.Channel, start, request.Budget, linked.Token)).ResponseAsync.ConfigureAwait(false);
Verify(wireMetadata.Serving, selected);
var metadata = DataProtoMapper.DecodeMetadataResponse(wireMetadata, Limits(budget, selected.Capabilities));
metadataValid = metadata.Count == legacy.Length && !metadata.Where((x, i) =>
x.CorrelationId != i.ToString(System.Globalization.CultureInfo.InvariantCulture) ||
x.Status != DataItemStatus.Good || x.Value is null || x.Value.View != items[legacy[i]].View ||
x.Value.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch || !x.Value.Writable ||
(x.Value.AllowedOperations & DataOperations.Write) == 0).Any();
if (metadataValid)
{
linked.Token.ThrowIfCancellationRequested(); Verify(wireMetadata.Serving, selected);
for (var i = 0; i < legacy.Length; i++) items[legacy[i]] = items[legacy[i]] with {
ExpectedCatalogRevision = metadata[i].Value!.CatalogRevision,
ExpectedServingIncarnation = selected.Capabilities.Serving.Incarnation };
}
}
catch (Exception ex) when (ex is RpcException or HttpRequestException or InvalidOperationException or ArgumentException or TimeoutException or OperationCanceledException)
{ if (cancellationToken.IsCancellationRequested || _scope.CancellationToken.IsCancellationRequested || _shutdown.IsCancellationRequested) break; }
}
if (!metadataValid)
{
deferred.AddRange(legacy.Select(i => eligible[i]));
var strict = Enumerable.Range(0, items.Length).Except(legacy).ToArray();
eligible = strict.Select(i => eligible[i]).ToArray();
items = strict.Select(i => items[i]).ToArray();
if (eligible.Length == 0) { eligible = deferred.ToArray(); continue; }
}
catch (Exception ex) when (ex is RpcException or InvalidOperationException or ArgumentException or TimeoutException or OperationCanceledException)
{ if (cancellationToken.IsCancellationRequested || _scope.CancellationToken.IsCancellationRequested) break; continue; }
}
items = items.Select(x => x.ExpectedServingGeneration is null ? x with { ExpectedServingGeneration = selected.Capabilities.Serving.ServingGeneration } : x).ToArray();
var elapsed = Clock.GetElapsedTime(start);
var live = Enumerable.Range(0, items.Length).Where(i => items[i].RemainingBudget > elapsed).ToArray();
foreach (var i in Enumerable.Range(0, items.Length).Except(live))
@@ -384,7 +424,7 @@ public sealed class GrpcDataConnection : IDataConnection
new(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "Item budget expired before dispatch."));
eligible = live.Select(i => eligible[i]).ToArray();
items = live.Select(i => items[i] with { RemainingBudget = items[i].RemainingBudget - elapsed }).ToArray();
if (eligible.Length == 0) break;
if (eligible.Length == 0) { eligible = deferred.ToArray(); continue; }
var dispatchStarted = false;
try
{
@@ -402,7 +442,7 @@ public sealed class GrpcDataConnection : IDataConnection
VerifyWriteEnvelope(wire.Serving, selected, decoded);
linked.Token.ThrowIfCancellationRequested();
for (var i = 0; i < eligible.Length; i++) results[eligible[i]] = decoded[i];
eligible = eligible.Where((_, i) => decoded[i].Outcome.State == DataWriteState.RejectedBeforeDispatch).ToArray();
eligible = deferred.Concat(eligible.Where((index, i) => request.Items[index].ExpectedServingGeneration is null && decoded[i].Outcome.State == DataWriteState.RejectedBeforeDispatch)).ToArray();
attempted = true;
}
catch (Exception ex) when (ex is RpcException or HttpRequestException or OperationCanceledException or InvalidOperationException or ArgumentException or TimeoutException)
@@ -410,7 +450,8 @@ public sealed class GrpcDataConnection : IDataConnection
if (dispatchStarted)
foreach (var index in eligible) results[index] = new(request.Items[index].CorrelationId,
new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown."));
break;
if (cancellationToken.IsCancellationRequested || _scope.CancellationToken.IsCancellationRequested || _shutdown.IsCancellationRequested) break;
eligible = dispatchStarted ? deferred.ToArray() : deferred.Concat(eligible).ToArray();
}
}
if (!attempted && eligible.Length > 0) ProbeFailed();
@@ -504,8 +545,9 @@ public sealed class GrpcDataConnection : IDataConnection
AsyncDuplexStreamingCall<W.SubscriptionCommand, W.SubscriptionFrame> call, Selected selected,
CancellationTokenSource lifetime, int maxBytes, int maxItems, int maxPendingCommands,
TimeSpan maxCommandTimeout, CommandStateBudget commandBudget, Func<string, long, bool> claimEpoch, Action<WeakReference>? observePending,
Func<Task>? afterTimerCancelled, Action release) : IDataSubscription
Func<Task>? afterTimerCancelled, Action release) : IDataSubscription, IDataSubscriptionProvenance
{
public ServingIdentity Serving { get; } = selected.Capabilities.Serving;
private readonly SemaphoreSlim _send = new(1, 1);
private readonly Task _headersReceipt = call.ResponseHeadersAsync;
private Dictionary<ulong, DataItemHandle> _handles = new();
@@ -0,0 +1,325 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>A connection lease remains owned until every operation using it has physically completed.</summary>
public interface IGrpcDataAdapterConnectionLease : IAsyncDisposable
{
IDataConnection Connection { get; }
CancellationToken CancellationToken { get; }
}
public interface IGrpcDataAdapterConnectionSource
{
ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken);
}
/// <summary>Trusted route and its live authority, supplied by the local projection catalog.</summary>
public sealed record GrpcDataAdapterRoute(string DependencyReference, DataView View, DataMetadata Metadata,
ServingIdentity Serving, IDataAuthorizationLease Lease, long ProjectionGeneration, TimeSpan MaximumSampleAge = default);
public interface IGrpcDataAdapterRouteSource
{
bool TryResolve(string fullReference, out GrpcDataAdapterRoute? route);
}
/// <summary>A publication route is trusted local placement, never a remote path inferred by the publisher.</summary>
public sealed record ProjectedValueRoute(string DriverInstanceId, string DependencyReference, DataRealm Realm,
string LocalIdentifier, long ProjectionGeneration, ServingIdentity Serving, Guid PublicationId = default);
public sealed record ProjectedValueUpdate(ProjectedValueRoute Route, DataValueSnapshot Snapshot, DataAgeBounds OriginAgeBounds,
long ReceivedTimestamp, IProjectedSamplePublicationProof SourceProof, bool IsCompleteSnapshot = false,
TimeSpan? MaximumSampleAge = null);
public interface IProjectedValuePublisher
{
bool TryBind(ProjectedValueRoute route);
bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates);
void Retire(ProjectedValueRoute route);
}
/// <summary>A driver facade over a configured, scoped data connection.</summary>
public sealed class GrpcDataDriverAdapter : IDriver, IBatchSubscribable, IWriteOutcomeCapability
{
private readonly string _connectionId;
private readonly IGrpcDataAdapterConnectionSource _source;
private readonly IGrpcDataAdapterRouteSource _routes;
private readonly IProjectedValuePublisher? _publisher;
private readonly object _sync = new();
private readonly HashSet<Subscription> _subscriptions = [];
private bool _running;
private long _epoch;
public GrpcDataDriverAdapter(string driverInstanceId, string connectionId,
IGrpcDataAdapterConnectionSource source, IGrpcDataAdapterRouteSource routes, IProjectedValuePublisher? publisher = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId);
ArgumentException.ThrowIfNullOrWhiteSpace(connectionId);
DriverInstanceId = driverInstanceId;
_connectionId = connectionId;
_source = source ?? throw new ArgumentNullException(nameof(source));
_routes = routes ?? throw new ArgumentNullException(nameof(routes));
_publisher = publisher;
}
public string DriverInstanceId { get; }
public string DriverType => "GrpcData";
public event EventHandler<DataChangeEventArgs>? OnDataChange;
public event EventHandler<DataChangeBatchEventArgs>? OnDataChangeBatch;
public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
lock (_sync) _running = true;
return Task.CompletedTask;
}
public async Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
await ShutdownAsync(cancellationToken).ConfigureAwait(false);
await InitializeAsync(driverConfigJson, cancellationToken).ConfigureAwait(false);
}
public DriverHealth GetHealth() { lock (_sync) return new(_running ? DriverState.Healthy : DriverState.Unknown, null, null); }
public async Task ShutdownAsync(CancellationToken cancellationToken)
{
Subscription[] pending;
lock (_sync) { _running = false; pending = _subscriptions.ToArray(); _subscriptions.Clear(); }
foreach (var subscription in pending) await subscription.CloseAsync().ConfigureAwait(false);
}
public async Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(writes);
var results = new DataWriteOutcome[writes.Count];
for (var i = 0; i < writes.Count; i++)
{
var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, 0x803B0000u, "Projection is unavailable.");
results[i] = rejected;
lock (_sync) { if (!_running) continue; }
if (!_routes.TryResolve(writes[i].FullReference, out var route) || route is null || !Valid(route)) continue;
await using var lease = await _source.AcquireAsync(_connectionId, cancellationToken).ConfigureAwait(false);
if (lease is null || lease.CancellationToken.IsCancellationRequested || !Valid(route)) continue;
using var value = OwnedDataSample.Copy(writes[i].Value);
var id = Guid.NewGuid().ToString("N");
var item = new WriteItem(id, Guid.NewGuid().ToString("N"), route.View, value,
route.Serving.CatalogEpoch, route.Serving.Incarnation, TimeSpan.FromSeconds(5), route.Serving.ServingGeneration);
try
{
var response = await lease.Connection.WriteAsync(new WriteBatch([item], new(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024)), cancellationToken).ConfigureAwait(false);
results[i] = response.Count == 1 && response[0].CorrelationId == id ? response[0].Outcome :
new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Uncorrelated write response.");
}
catch (Exception) when (!cancellationToken.IsCancellationRequested)
{ results[i] = new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write completion is unknown."); }
}
return results;
}
private static object DecodeArray(DataValue value)
{
var elements = value.GetArray();
return value.ArrayElementKind switch
{
DataValueKind.Boolean => elements.Cast<bool>().ToArray(), DataValueKind.Int8 => elements.Cast<sbyte>().ToArray(),
DataValueKind.UInt8 => elements.Cast<byte>().ToArray(), DataValueKind.Int16 => elements.Cast<short>().ToArray(),
DataValueKind.UInt16 => elements.Cast<ushort>().ToArray(), DataValueKind.Int32 => elements.Cast<int>().ToArray(),
DataValueKind.UInt32 => elements.Cast<uint>().ToArray(), DataValueKind.Int64 => elements.Cast<long>().ToArray(),
DataValueKind.UInt64 => elements.Cast<ulong>().ToArray(), DataValueKind.Float => elements.Cast<float>().ToArray(),
DataValueKind.Double => elements.Cast<double>().ToArray(), DataValueKind.String => elements.Cast<string>().ToArray(),
DataValueKind.Timestamp => elements.Cast<DateTimeOffset>().Select(timestamp => timestamp.UtcDateTime).ToArray(),
_ => throw new InvalidOperationException("Unsupported projected array element type.")
};
}
private static bool Valid(GrpcDataAdapterRoute route) => route.Lease.IsValid && route.Lease.Serving == route.Serving &&
route.Serving.ServingGeneration > 0 && route.Metadata.View == route.View;
public async Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(fullReferences);
lock (_sync) { if (!_running) throw new InvalidOperationException("Driver is stopped."); }
var routes = fullReferences.Select(reference => _routes.TryResolve(reference, out var route) && route is not null && Valid(route)
? route : throw new InvalidOperationException("Projection is unavailable.")).ToArray();
if (routes.Length == 0 || routes.Any(r => r.Serving != routes[0].Serving)) throw new InvalidOperationException("Incompatible projection authority.");
var lease = await _source.AcquireAsync(_connectionId, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException("Connection is unavailable.");
IDataSubscription? stream = null;
try
{
stream = await lease.Connection.SubscribeAsync(cancellationToken).ConfigureAwait(false);
if (stream is not IDataSubscriptionProvenance proof || proof.Serving != routes[0].Serving || routes.Any(r => !Valid(r)))
throw new InvalidOperationException("Subscription authority changed.");
var epoch = Interlocked.Increment(ref _epoch);
var id = Guid.NewGuid().ToString("N");
var subscription = new Subscription(this, lease, stream, routes, id, epoch);
lock (_sync)
{
if (!_running) throw new InvalidOperationException("Driver is stopped.");
_subscriptions.Add(subscription);
}
try
{
var settings = new DataSubscriptionSettings(publishingInterval, publishingInterval, DataChangeTrigger.StatusValueTimestamp, null);
var items = routes.Select((route, index) => new DataSubscriptionItem(index.ToString(System.Globalization.CultureInfo.InvariantCulture), route.View, settings)).ToArray();
await stream.SendAsync(new OpenSubscription(id, epoch, Guid.NewGuid().ToString("N"), TimeSpan.FromSeconds(5), items, false,
TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), items.Length, 4 * 1024 * 1024)), cancellationToken).ConfigureAwait(false);
subscription.Start();
return subscription;
}
catch { lock (_sync) _subscriptions.Remove(subscription); await subscription.CloseAsync().ConfigureAwait(false); stream = null; lease = null!; throw; }
}
catch
{
if (stream is not null) await stream.DisposeAsync().ConfigureAwait(false);
if (lease is not null) await lease.DisposeAsync().ConfigureAwait(false);
throw;
}
}
public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken)
{
if (handle is not Subscription subscription || subscription.Owner != this) throw new ArgumentException("Unknown subscription.", nameof(handle));
lock (_sync) _subscriptions.Remove(subscription);
await subscription.CloseAsync().ConfigureAwait(false);
}
private sealed class Subscription(GrpcDataDriverAdapter owner, IGrpcDataAdapterConnectionLease lease,
IDataSubscription stream, GrpcDataAdapterRoute[] routes, string id, long epoch) : ISubscriptionHandle
{
private readonly CancellationTokenSource _stop = CancellationTokenSource.CreateLinkedTokenSource(lease.CancellationToken);
private readonly object _closeSync = new();
private Task? _close;
private Task? _reader;
private readonly SampleProof _proof = new(lease.Connection.Clock, routes, lease.CancellationToken);
private readonly List<ProjectedValueRoute> _bound = [];
public GrpcDataDriverAdapter Owner => owner;
public string DiagnosticId => id;
public void Start() => _reader = ReadAsync();
public Task CloseAsync() { lock (_closeSync) return _close ??= CloseCoreAsync(); }
private async Task CloseCoreAsync()
{
_proof.Invalidate();
_stop.Cancel();
ProjectedValueRoute[] retired;
lock (_closeSync) { retired = _bound.ToArray(); _bound.Clear(); }
foreach (var route in retired) owner._publisher?.Retire(route);
try { await stream.DisposeAsync().ConfigureAwait(false); }
finally
{
try { if (_reader is not null) await _reader.ConfigureAwait(false); }
catch (OperationCanceledException) { }
finally { await lease.DisposeAsync().ConfigureAwait(false); _stop.Dispose(); }
}
}
private async Task ReadAsync()
{
var handles = new Dictionary<DataItemHandle, GrpcDataAdapterRoute>();
long sequence = 0;
var snapshot = false;
var ready = false;
var pending = new List<ProjectedValueUpdate>();
long pendingBytes = 0;
var publishedRoutes = new Dictionary<string, ProjectedValueRoute>(StringComparer.Ordinal);
foreach (var route in routes)
{
if (!ProjectedDataIds.TryParseDependencyReference(route.DependencyReference, out var realm, out var identifier))
{ _proof.Invalidate(); return; }
publishedRoutes[route.DependencyReference] = new(owner.DriverInstanceId, route.DependencyReference, realm,
identifier, route.ProjectionGeneration, route.Serving, Guid.NewGuid());
}
bool Publish(IReadOnlyList<ProjectedValueUpdate> updates)
{
if (owner._publisher is null || !_proof.IsValid) { _proof.Invalidate(); return false; }
if (!owner._publisher.TryPublish(updates)) { _proof.Invalidate(); return false; }
if (!_proof.IsValid) return false;
var legacy = updates.Select(update => new DataChangeItem(update.Route.DependencyReference, update.Snapshot)).ToArray();
if (legacy.Length > 0)
{
owner.OnDataChangeBatch?.Invoke(owner, new(this, legacy));
foreach (var item in legacy) owner.OnDataChange?.Invoke(owner, new(this, item.FullReference, item.Snapshot));
}
return _proof.IsValid;
}
try
{
await foreach (var frame in stream.ReadAllAsync(_stop.Token).ConfigureAwait(false))
{
try
{
if (frame.SubscriptionId != id || frame.StreamEpoch != epoch || frame.Sequence <= sequence || routes.Any(r => !Valid(r))) break;
sequence = frame.Sequence;
if (frame is DataSubscriptionAck ack)
{
foreach (var item in ack.Items)
if (item.Status == DataItemStatus.Good && item.Handle is not null && int.TryParse(item.ClientItemId, out var index) && index >= 0 && index < routes.Length)
handles[item.Handle] = routes[index];
}
else if (frame is DataSubscriptionControl control)
{
if (control.CatalogEpoch != routes[0].Serving.CatalogEpoch || control.AuthorityEpoch != routes[0].Serving.AuthorityEpoch) break;
if (control.Kind == DataStreamControlKind.SnapshotBegin) { snapshot = true; ready = false; pending.Clear(); pendingBytes = 0; }
else if (control.Kind == DataStreamControlKind.SnapshotEnd && snapshot)
{
snapshot = false;
foreach (var projected in publishedRoutes.Values)
{
if (owner._publisher is null || !owner._publisher.TryBind(projected)) { _proof.Invalidate(); break; }
lock (_closeSync) _bound.Add(projected);
if (!_proof.IsValid)
{
lock (_closeSync) _bound.Remove(projected);
owner._publisher.Retire(projected);
break;
}
}
if (!_proof.IsValid || (pending.Count > 0 && !Publish(pending.Select(update =>
update with { IsCompleteSnapshot = true }).ToArray()))) break;
pending.Clear(); pendingBytes = 0; ready = true;
}
else if (control.Kind is DataStreamControlKind.Reset or DataStreamControlKind.CatalogInvalidated or DataStreamControlKind.AuthorityInvalidated) break;
}
else if (frame is DataSubscriptionValues values && (snapshot || ready))
{
var batch = new List<ProjectedValueUpdate>();
foreach (var item in values.Items)
{
if (!handles.TryGetValue(item.Handle, out var route) || item.Sample.Serving != route.Serving ||
!Valid(route) || item.Readiness != DataReadiness.Ready) { _proof.Invalidate(); break; }
var value = item.Sample.Value;
if (value.Kind == DataValueKind.Array) { _proof.Invalidate(); break; }
item.AgeBounds.Validate();
var bytes = value.EstimatedRetainedBytes;
pendingBytes = checked(pendingBytes + bytes);
if (pendingBytes > 4 * 1024 * 1024 || pending.Count + batch.Count >= 4096) { _proof.Invalidate(); break; }
object? payload = value.Kind switch { DataValueKind.Null => null, DataValueKind.Bytes => value.GetBytes().ToArray(),
DataValueKind.Array => DecodeArray(value), _ => value.GetScalar() };
var legacy = new DataValueSnapshot(payload, item.Sample.StatusCode,
item.Sample.SourceTimestampUtc?.UtcDateTime, item.Sample.ServerTimestampUtc?.UtcDateTime);
batch.Add(new(publishedRoutes[route.DependencyReference], legacy, item.AgeBounds,
lease.Connection.Clock.GetTimestamp(), _proof, MaximumSampleAge: route.MaximumSampleAge));
}
if (!_proof.IsValid) break;
if (snapshot) pending.AddRange(batch);
else
{
if (batch.Count > 0 && !Publish(batch)) break;
pendingBytes = 0;
}
}
}
finally { (frame as IDisposable)?.Dispose(); }
}
}
catch (OperationCanceledException) when (_stop.IsCancellationRequested) { }
finally { if (!_stop.IsCancellationRequested) _proof.Invalidate(); }
}
private sealed class SampleProof(TimeProvider clock, GrpcDataAdapterRoute[] routes, CancellationToken cancellationToken)
: IProjectedSamplePublicationProof
{
private int _invalid;
public TimeProvider Clock => clock;
public bool IsValid => Volatile.Read(ref _invalid) == 0 && !cancellationToken.IsCancellationRequested && routes.All(Valid);
public void Invalidate() => Interlocked.Exchange(ref _invalid, 1);
}
}
}
@@ -0,0 +1,7 @@
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Receives aggregate configured dependency transitions without blocking the mux actor.</summary>
public interface IProjectedDependencyInterestSink
{
void SetInterest(string projectedReference, bool active);
}
@@ -28,6 +28,20 @@ public sealed class LocalCatalogCoordinator
private LocalExportCatalog? _published;
private bool _terminal;
private bool _catalogValid;
private ProjectedMappingDeploymentRuntime? _projectedMappings;
internal ProjectedMappingDeploymentRuntime? ProjectedMappings => Volatile.Read(ref _projectedMappings);
internal void AttachProjectedMappings(ProjectedMappingDeploymentRuntime runtime)
{
if (Interlocked.CompareExchange(ref _projectedMappings, runtime, null) is not null)
throw new InvalidOperationException("Projected mappings are already attached.");
}
internal void DetachProjectedMappings(ProjectedMappingDeploymentRuntime runtime) =>
Interlocked.CompareExchange(ref _projectedMappings, null, runtime);
internal LocalExportCatalog? MappingCatalog(CatalogAttempt attempt)
{
lock (_gate)
return ReferenceEquals(_attempt, attempt) && _terminal ? Current : null;
}
// A test can hold the host's existing subscription boundary to observe ordering.
internal Action? BeforeSubscriptionApplyForTests { get; set; }
@@ -84,16 +98,18 @@ public sealed class LocalCatalogCoordinator
public CatalogAttempt BeginAttempt(string revision)
{
CatalogAttempt attempt;
lock (_gate)
{
var attempt = new CatalogAttempt(_activation.Begin(revision), revision);
attempt = new CatalogAttempt(_activation.Begin(revision), revision);
_attempt = attempt;
_staged = null;
_terminal = false;
_catalogValid = false;
using (DispatchFence.Enter()) Volatile.Write(ref _published, null);
return attempt;
}
ProjectedMappings?.AttemptBegan(attempt);
return attempt;
}
/// <summary>Install independently readable credentials even when catalog topology is invalid.</summary>
@@ -136,6 +152,7 @@ public sealed class LocalCatalogCoordinator
public bool Complete(CatalogAttempt attempt, bool topologySucceeded)
{
ArgumentNullException.ThrowIfNull(attempt);
bool completed;
lock (_gate)
{
if (_terminal || !ReferenceEquals(_attempt, attempt)) return false;
@@ -144,12 +161,10 @@ public sealed class LocalCatalogCoordinator
var valid = topologySucceeded && _staged is not null && _catalogValid
&& state.AuthorityEpoch == _authority.Current.GenerationId;
if (valid) { using (DispatchFence.Enter()) Volatile.Write(ref _published, _staged); }
if (!_activation.Complete(attempt.Epoch, valid))
{
using (DispatchFence.Enter()) Volatile.Write(ref _published, null);
return false;
}
return true;
completed = _activation.Complete(attempt.Epoch, valid);
if (!completed) { using (DispatchFence.Enter()) Volatile.Write(ref _published, null); }
}
ProjectedMappings?.AttemptCompleted(attempt, completed);
return completed;
}
}
@@ -202,7 +202,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
&& (operation != DataOperations.Write || node.Metadata.Writable
&& string.Equals(_capabilities.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase))
&& Allowed(catalog, context, node, operation)) operations |= operation;
return node.Metadata with { AllowedOperations = operations, Writable = node.Metadata.Writable && operations.HasFlag(DataOperations.Write) };
return node.Metadata with { AllowedOperations = operations, Writable = node.Metadata.Writable && operations.HasFlag(DataOperations.Write), Serving = catalog.Serving };
}
internal Task<DataCapabilities> GetCapabilitiesAsync(DataAuthenticatedContext context, DataTarget target, DataBudget budget, CancellationToken cancellationToken)
@@ -214,7 +214,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
catalog is null ? _capabilities.Limits : Limits(catalog, context));
if (catalog is null || !Ready(catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving))
capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None };
return Task.FromResult(capabilities);
return Task.FromResult(capabilities with { WriteServingGenerationEnforced = true, ProtocolMinor = Math.Max(3, capabilities.ProtocolMinor) });
}
internal Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(DataAuthenticatedContext context, DataTarget target, MetadataRequest request, CancellationToken cancellationToken)
@@ -375,7 +375,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
var token = complete ? null : EncodeContinuation(new(request.Parent, request.Filter, offset, context.PrincipalId,
context.ApiKeyId, context.CredentialVersion, catalog.Serving, start, leaseDuration.Ticks));
return Task.FromResult(new DataBrowseBranch(request.Parent, DataItemStatus.Good, page, complete, token,
new MetadataLease(catalog.Serving.CatalogEpoch, catalog.Serving.AuthorityEpoch, leaseDuration)));
new MetadataLease(catalog.Serving.CatalogEpoch, catalog.Serving.AuthorityEpoch, leaseDuration), catalog.Serving));
}
internal async Task<IReadOnlyList<WriteItemResult>> WriteAsync(DataAuthenticatedContext context, WriteBatch request, CancellationToken cancellationToken)
@@ -391,7 +391,8 @@ public sealed class LocalDataServices : IDataConnectionFactory
if (_writes is not null && catalog is not null && Ready(catalog)
&& string.Equals(_capabilities.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)
&& catalog.TryResolve(item.View, out var node)
&& node.SourceEnabled && node.Supported && node.Metadata.Writable && Allowed(catalog, context, node, DataOperations.Write))
&& node.SourceEnabled && node.Supported && node.Metadata.Writable && Allowed(catalog, context, node, DataOperations.Write)
&& (item.ExpectedServingGeneration is null || item.ExpectedServingGeneration > 0 && item.ExpectedServingGeneration == catalog.Serving.ServingGeneration))
{ allowed.Add(item); indexes.Add(i); }
else results[i] = new(item.CorrelationId, new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Write unavailable or denied before dispatch."));
}
@@ -97,6 +97,7 @@ public sealed partial class LocalExportCatalog
public string ClusterId { get; }
public ServingIdentity Serving { get; }
internal IDataMappedCatalogAuthority MappingAuthority => _activation;
public long AuthorityEpoch => _activation.AuthorityEpoch;
public bool IsActive => _activation.IsActive && _activation.CatalogEpoch == Serving.CatalogEpoch
&& _activation.AuthorityEpoch == Serving.AuthorityEpoch;
@@ -0,0 +1,51 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Resolves canonical projected references while retaining their original local and origin authority.</summary>
public sealed class ProjectedAdapterRouteSource(IFederatedProjectionCatalog catalog,
Func<string, string?> connectionForMapping, string connectionId, Func<ProjectedNodeProof, bool> authorize)
: IGrpcDataAdapterRouteSource
{
private bool Current(DataRealm realm, string identifier, out ProjectedNodeProof? proof)
{
proof = null;
try
{
if (!catalog.TryResolveProjected(realm, identifier, out var found) || found is null ||
found.Metadata.View.MappingId is not { } mapping || found.Generation <= 0 ||
found.LocalIdentifier != identifier || found.Metadata.View.Realm != realm ||
!found.Lease.IsValid || found.Lease.Serving.ServingGeneration <= 0 ||
found.Metadata.Serving != found.Lease.Serving || found.OriginMetadata.Serving != found.Lease.Serving ||
found.OriginMetadata.View.MappingId is not null || found.OriginMetadata.View.MappingRevision != 0 ||
found.OriginMetadata.View.Address != found.Metadata.View.Address || found.OriginMetadata.View.Realm != realm ||
found.Resolver.Resolve(found.Metadata.View, found.Subject).Kind != MappedSubjectResolutionKind.Mapped ||
!string.Equals(connectionForMapping(mapping), connectionId, StringComparison.OrdinalIgnoreCase) || !authorize(found))
return false;
proof = found;
return true;
}
catch (Exception) { return false; }
}
public bool TryResolve(string fullReference, out GrpcDataAdapterRoute? route)
{
route = null;
if (!ProjectedDataIds.TryParseDependencyReference(fullReference, out var realm, out var identifier) ||
!Current(realm, identifier, out var proof) || proof is null) return false;
var captured = proof;
var lease = new RouteLease(captured.Lease.Serving, () => Current(realm, identifier, out var now) && now is not null &&
now.Generation == captured.Generation && now.Lease.Serving == captured.Lease.Serving &&
now.OriginMetadata == captured.OriginMetadata && now.Metadata.View == captured.Metadata.View && captured.Lease.IsValid);
route = new(fullReference, captured.OriginMetadata.View, captured.OriginMetadata, captured.Lease.Serving, lease,
captured.Generation, captured.MaximumSampleAge);
return lease.IsValid;
}
private sealed class RouteLease(ServingIdentity serving, Func<bool> current) : IDataAuthorizationLease
{
public ServingIdentity Serving => serving;
public bool IsValid => current();
}
}
@@ -0,0 +1,224 @@
using System.Collections.Concurrent;
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Caller-bound projection browse scheduling and local anchor lifetime.</summary>
public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
{
private sealed record Installed(NodeId Node, ProjectedAnchorDefinition Definition, ProjectedMappingPlacement Placement);
private readonly record struct WorkKey(NodeId Parent, DataCallerIdentity Caller, string? Cursor, int MaxItems);
private readonly ProjectedMappingDeploymentRuntime _lifecycle;
private readonly IFederatedProjectionCatalog _catalog;
private readonly ProjectedNamespaceApplier _applier;
private readonly IProjectedAnchorSink _anchors;
private readonly Func<string, string, NodeId?> _resolveNode;
private readonly DataBudget _budget;
private readonly int _maxPending;
private readonly object _anchorGate = new();
private readonly ConcurrentDictionary<string, Installed> _installed = new(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<WorkKey, TaskCompletionSource> _inflight = new();
private readonly record struct Failure(ProjectionPageStatus Status, long Until);
private readonly object _resultGate = new();
private readonly Dictionary<WorkKey, Failure> _failures = new();
private readonly CancellationTokenSource _stop = new();
private int _pending, _disposed;
public ProjectedBrowseAccess(ProjectedMappingDeploymentRuntime lifecycle, IFederatedProjectionCatalog catalog,
ProjectedNamespaceApplier applier, IProjectedAnchorSink anchors, Func<string, string, NodeId?> resolveNode,
DataBudget budget, int maxPending)
{
_lifecycle = lifecycle ?? throw new ArgumentNullException(nameof(lifecycle));
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
_applier = applier ?? throw new ArgumentNullException(nameof(applier));
_anchors = anchors ?? throw new ArgumentNullException(nameof(anchors));
_resolveNode = resolveNode ?? throw new ArgumentNullException(nameof(resolveNode));
_budget = budget ?? throw new ArgumentNullException(nameof(budget)); _budget.Validate();
if (maxPending <= 0) throw new ArgumentOutOfRangeException(nameof(maxPending));
_maxPending = maxPending;
_lifecycle.Changed += OnChanged;
RefreshAnchors();
}
private void OnChanged(IReadOnlyList<ProjectedMappingPlacement> _) => RefreshAnchors();
private bool Current(ProjectedMappingPlacement placement) => _lifecycle.IsCurrentPlacement(placement);
/// <summary>Reconciles against the live SDK binding; safe to call after the deferred sink binds.</summary>
public void RefreshAnchors()
{
lock (_anchorGate)
{
if (Volatile.Read(ref _disposed) != 0) return;
var placements = _lifecycle.Active;
foreach (var entry in _installed.ToArray())
{
var old = entry.Value;
if (Current(old.Placement)) continue;
_installed.TryRemove(entry.Key, out _);
_anchors.TryRemoveProjectedAnchor(old.Node, old.Definition);
}
foreach (var placement in placements)
{
var mappingId = placement.Mapping.RemoteNamespaceMappingId;
if (_installed.ContainsKey(mappingId) || !Current(placement) || placement.Parent.Address.IdentifierKind != "string") continue;
var parent = _resolveNode(placement.Parent.Address.NamespaceUri, placement.Parent.Address.Identifier);
if (parent is not { } parentNode) continue;
var id = ProjectedDataIds.Identifier(mappingId, placement.Anchor.Address);
var definition = new ProjectedAnchorDefinition(placement.Mapping.Realm, id, parentNode, placement.Mapping.BranchName,
placement.Anchor.Subject, mappingId, placement.Mapping.Revision, () => Current(placement));
if (_anchors.TryEnsureProjectedAnchor(definition, out var node) && node is { } anchorNode)
{
if (Current(placement)) _installed[mappingId] = new(anchorNode, definition, placement);
else _anchors.TryRemoveProjectedAnchor(anchorNode, definition);
}
}
}
}
private sealed class PageGuard(ProjectedBrowseAccess owner, IProjectedPageGuard source)
{
public bool IsCurrent() => Volatile.Read(ref owner._disposed) == 0 && source.IsCurrent;
}
private static ProjectedBrowsePage Empty(ProjectedBrowseReadiness status) => new(status, [], null, false, static () => false);
public ProjectedBrowsePage GetOrSchedulePage(ProjectedBrowsePageRequest input)
{
ArgumentNullException.ThrowIfNull(input);
if (Volatile.Read(ref _disposed) != 0) return Empty(ProjectedBrowseReadiness.Unavailable);
var id = input.Parent.IdentifierAsString;
if (!ProjectedDataIds.TryDecodeIdentifier(id, out var mappingId, out _)) return Empty(ProjectedBrowseReadiness.Unavailable);
if (!_installed.TryGetValue(mappingId, out var anchor) || !Current(anchor.Placement)) return Empty(ProjectedBrowseReadiness.Unavailable);
DataView parent;
if (anchor.Node == input.Parent) parent = anchor.Placement.Anchor;
else
{
var realm = anchor.Placement.Mapping.Realm;
var expected = _resolveNode(ProjectedDataIds.NamespaceUri(realm), id);
if (expected != input.Parent || !_catalog.TryResolveProjected(realm, id, out var proof) || proof is null ||
proof.Subject.View.MappingId != mappingId || !proof.Lease.IsValid || !ReferenceEquals(proof.Resolver.LocalAuthority, anchor.Placement.Authority))
return Empty(ProjectedBrowseReadiness.Unavailable);
parent = proof.Metadata.View;
}
var caller = input.Caller;
if (caller is null || string.IsNullOrWhiteSpace(caller.Principal) || string.IsNullOrWhiteSpace(caller.ApiKeyId) ||
string.IsNullOrWhiteSpace(caller.CredentialVersion)) return Empty(ProjectedBrowseReadiness.Unavailable);
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
var maximum = input.MaximumResults == 0 ? _budget.MaxItems : (int)Math.Min((long)input.MaximumResults, _budget.MaxItems);
var budget = _budget with { MaxItems = maximum };
var request = new ProjectedBrowseRequest(mappingId, parent, null, input.Cursor, identity, budget, input.RequestStartedTimestamp);
var snapshot = _catalog.TryGetParent(request);
if (snapshot.Status == ProjectionPageStatus.Ready)
{
if (snapshot.Lease is not { IsValid: true } lease || snapshot.LocalAuthority is not { IsActive: true } local ||
!ReferenceEquals(local, anchor.Placement.Authority) || snapshot.Generation <= 0)
return Empty(ProjectedBrowseReadiness.Unavailable);
var nodes = new List<NodeId>(snapshot.Items.Count);
foreach (var item in snapshot.Items)
{
if (item.Generation != snapshot.Generation || !ReferenceEquals(item.Resolver.LocalAuthority, local) || !item.Lease.IsValid ||
item.Subject.View.MappingId != mappingId || _resolveNode(ProjectedDataIds.NamespaceUri(item.Metadata.View.Realm), item.LocalIdentifier) is not { } node)
return Empty(ProjectedBrowseReadiness.Unavailable);
nodes.Add(node);
}
var expectedIds = nodes.ToArray();
var sourceGuard = _catalog.CaptureParentGuard(request, snapshot);
if (sourceGuard is null) return Empty(ProjectedBrowseReadiness.Unavailable);
var guard = new PageGuard(this, sourceGuard);
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));
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);
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 (_failures.TryGetValue(key, out var failure))
return Empty(failure.Status switch
{
ProjectionPageStatus.InvalidContinuation => ProjectedBrowseReadiness.InvalidContinuation,
ProjectionPageStatus.Pending => ProjectedBrowseReadiness.Pending,
_ => 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);
_pending++;
}
var exactParent = input.Parent;
_ = Task.Run(async () =>
{
var result = ProjectionPageStatus.Unavailable;
try { if (Current(anchor.Placement)) result = await _applier.ApplyPageResultAsync(request, exactParent, _stop.Token).ConfigureAwait(false); }
catch (Exception) { }
finally
{
lock (_resultGate)
{
_inflight.TryRemove(key, out var completed);
_pending--;
if (result != ProjectionPageStatus.Ready && !_stop.IsCancellationRequested)
{
var now = _catalog.Clock.GetTimestamp();
var seconds = result == ProjectionPageStatus.InvalidContinuation ? 60L : 0L;
var delay = seconds == 0 ? Math.Max(1, _catalog.Clock.TimestampFrequency / 4) :
_catalog.Clock.TimestampFrequency > long.MaxValue / seconds ? long.MaxValue : _catalog.Clock.TimestampFrequency * seconds;
_failures[key] = new(result, now > long.MaxValue - delay ? long.MaxValue : now + delay);
}
completed?.TrySetResult();
}
}
});
return Empty(ProjectedBrowseReadiness.Pending);
}
public async Task<ProjectedBrowsePage> WaitForPageAsync(ProjectedBrowsePageRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
for (var retry = 0; retry < 3; retry++)
{
var page = GetOrSchedulePage(request);
if (page.Status != ProjectedBrowseReadiness.Pending) return page;
var caller = request.Caller;
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
var max = request.MaximumResults == 0 ? _budget.MaxItems : (int)Math.Min((long)request.MaximumResults, _budget.MaxItems);
var key = new WorkKey(request.Parent, identity, request.Cursor, max);
if (!_inflight.TryGetValue(key, out var pending)) continue;
var elapsed = _catalog.Clock.GetElapsedTime(request.RequestStartedTimestamp, _catalog.Clock.GetTimestamp());
var remaining = _budget.Timeout - elapsed;
if (elapsed < TimeSpan.Zero || remaining <= TimeSpan.Zero) return Empty(ProjectedBrowseReadiness.Unavailable);
try { await pending.Task.WaitAsync(remaining, _catalog.Clock, cancellationToken).ConfigureAwait(false); }
catch (TimeoutException) { return Empty(ProjectedBrowseReadiness.Unavailable); }
}
return Empty(ProjectedBrowseReadiness.Unavailable);
}
public ProjectedBrowseReadiness GetOrSchedule(ProjectedBrowseContext context)
{
ArgumentNullException.ThrowIfNull(context);
if (!ProjectedDataIds.TryDecodeIdentifier(context.Parent.IdentifierAsString, out _, out _)) return ProjectedBrowseReadiness.Ready;
if (context.Caller is null) return ProjectedBrowseReadiness.Unavailable;
var page = GetOrSchedulePage(new(context.Parent, context.Caller, null, context.Continuation.MaxResultsToReturn, context.RequestStartedTimestamp));
return page.Status == ProjectedBrowseReadiness.Ready && !page.Complete ? ProjectedBrowseReadiness.Unavailable : page.Status;
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
_lifecycle.Changed -= OnChanged;
_stop.Cancel();
lock (_resultGate) _failures.Clear();
lock (_anchorGate)
{
foreach (var item in _installed.Values) _anchors.TryRemoveProjectedAnchor(item.Node, item.Definition);
_installed.Clear();
}
}
}
@@ -0,0 +1,379 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Observable per-parent projection status; pending and unavailable are not empty success.</summary>
public enum ProjectionPageStatus { Pending, Ready, Unavailable, InvalidContinuation }
/// <summary>One trusted immutable mapped subject and its currently leased remote authority.</summary>
public sealed record ProjectedNodeProof(string LocalIdentifier, DataMetadata Metadata, MappedNamespaceSubject Subject,
MappedSubjectResolver Resolver, IDataAuthorizationLease Lease, long Generation, DataMetadata OriginMetadata, TimeSpan MaximumSampleAge = default);
/// <summary>A caller-bound projection page.</summary>
public sealed record ProjectedParentSnapshot(ProjectionPageStatus Status, IReadOnlyList<ProjectedNodeProof> Items,
bool Complete, string? Continuation, long Generation, IDataAuthorizationLease? Lease = null,
IDataMappedCatalogAuthority? LocalAuthority = null, ProjectedNodeProof? ParentProof = null);
/// <summary>One bounded parent query, with the original monotonic request-start timestamp.</summary>
public sealed record ProjectedBrowseRequest(string MappingId, DataView Parent, string? Filter, string? Continuation,
DataCallerIdentity Caller, DataBudget Budget, long RequestStartedTimestamp)
{
internal ConfiguredProjectionCapability? ConfiguredCapability { get; init; }
}
/// <summary>Prepared pages are committed only after the caller successfully applies their content.</summary>
public interface IProjectedPreparedPage : IDisposable
{
ProjectedParentSnapshot Snapshot { get; }
bool TryCommit();
}
/// <summary>Detached constant-work validity of one already-authorized cached page.</summary>
public interface IProjectedPageGuard
{
bool IsCurrent { get; }
long RetainedBytes { get; }
}
/// <summary>Nonblocking catalog lookups and bounded asynchronous page preparation.</summary>
public interface IFederatedProjectionCatalog
{
TimeProvider Clock { get; }
ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request);
IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) => null;
Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken);
bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof);
bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin);
event Action<string, long>? Invalidated;
}
/// <summary>Bounded cache of caller-scoped, already-authorized projected pages.</summary>
public sealed class ProjectedCatalogCache
{
private readonly record struct ParentKey(string Mapping, DataView Parent, string? Filter, string? Cursor, DataCallerIdentity? Caller, ConfiguredProjectionCapability? Capability);
private sealed class ParentEntry(ProjectedParentSnapshot snapshot) { internal readonly object Version = new(); internal ProjectedParentSnapshot Snapshot = snapshot; internal LinkedListNode<ParentKey>? Sweep; }
private sealed class NodeEntry(ProjectedNodeProof proof) { internal ProjectedNodeProof Proof = proof; internal int Pins; internal bool Retired; internal LinkedListNode<(DataRealm Realm, string Id)>? Sweep; }
private readonly object _sync = new();
private readonly Dictionary<ParentKey, ParentEntry> _parents = new();
private readonly Dictionary<(DataRealm Realm, string Id), NodeEntry> _nodes = new();
private readonly HashSet<NodeEntry> _retiredPinned = new();
private readonly LinkedList<ParentKey> _parentSweep = new();
private readonly LinkedList<(DataRealm Realm, string Id)> _nodeSweep = new();
private readonly Dictionary<string, int> _mappingNodeCounts = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<(string Mapping, DataView Parent), Dictionary<string, (DataAddress Address, int Count)>> _siblingNames = new();
private long _retainedBytes;
private readonly Dictionary<(string Mapping, DataView Parent), long> _unavailable = new();
private readonly Dictionary<string, long> _mappingGenerations = new(StringComparer.OrdinalIgnoreCase);
private readonly int _maxParents, _maxNodes;
private readonly long _maxBytes;
private bool _saturated;
private long _nextGeneration;
private readonly DataOperationPolicy? _policy;
public ProjectedCatalogCache(int maxParents, int maxNodes, TimeProvider clock, DataOperationPolicy? policy = null, long maxBytes = 16 * 1024 * 1024)
{
if (maxParents <= 0 || maxNodes <= 0 || maxBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxParents));
_maxParents = maxParents; _maxNodes = maxNodes; _maxBytes = maxBytes; Clock = clock ?? throw new ArgumentNullException(nameof(clock)); _policy = policy;
}
public TimeProvider Clock { get; }
public event Action<string, long>? Invalidated;
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 &&
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 &&
proof.OriginMetadata.View.Address == proof.Metadata.View.Address && proof.OriginMetadata.View.Realm == proof.Metadata.View.Realm &&
proof.OriginMetadata.CatalogRevision == proof.Lease.Serving.CatalogEpoch &&
proof.LocalIdentifier == ProjectedDataIds.Identifier(proof.Subject.View.MappingId!, proof.OriginMetadata.View.Address) &&
proof.Resolver.Resolve(proof.Metadata.View, proof.Subject).Kind == MappedSubjectResolutionKind.Mapped;
private bool Valid(ProjectedNodeProof proof)
{
try { return ValidCore(proof); }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NullReferenceException) { return false; }
}
private static ProjectedNodeProof Freeze(ProjectedNodeProof proof) => proof with
{
Metadata = proof.Metadata with { Dimensions = Array.AsReadOnly(proof.Metadata.Dimensions.ToArray()) },
OriginMetadata = proof.OriginMetadata with { Dimensions = Array.AsReadOnly(proof.OriginMetadata.Dimensions.ToArray()) },
Subject = proof.Subject with
{
Scope = proof.Subject.Scope with { Segments = Array.AsReadOnly(proof.Subject.Scope.Segments.ToArray()) },
LocalAncestry = Array.AsReadOnly(proof.Subject.LocalAncestry.ToArray())
}
};
internal static bool IsValueNode(DataMetadata metadata) => metadata.NodeKind is "Variable" or "Tag";
private static long Bytes(ProjectedNodeProof proof) => ProjectedProofSize.Estimate(proof);
private static long KeyBytes(ParentKey k) => checked(256L + 2L * (k.Mapping.Length + k.Parent.Subject.Length +
k.Parent.Address.OriginClusterId.Length + k.Parent.Address.NamespaceUri.Length + k.Parent.Address.IdentifierKind.Length +
k.Parent.Address.Identifier.Length + (k.Parent.MappingId?.Length ?? 0) + (k.Filter?.Length ?? 0) +
(k.Cursor?.Length ?? 0) + (k.Caller?.Principal.Length ?? 0) + (k.Caller?.ApiKeyId?.Length ?? 0) + (k.Caller?.CredentialVersion?.Length ?? 0)));
private static long PageBytes(ParentKey key, ProjectedParentSnapshot page) => checked(KeyBytes(key) +
(page.ParentProof is { } parent ? Bytes(parent) : 0) + page.Items.Sum(Bytes));
private void ChangeMappingCount(NodeEntry entry, int delta)
{
var mapping = entry.Proof.Subject.View.MappingId!;
_mappingNodeCounts.TryGetValue(mapping, out var current);
if (current + delta == 0) _mappingNodeCounts.Remove(mapping); else _mappingNodeCounts[mapping] = checked(current + delta);
}
private void RemoveParent(ParentKey key)
{
if (!_parents.Remove(key, out var entry)) return;
_parentSweep.Remove(entry.Sweep!); _retainedBytes -= PageBytes(key, entry.Snapshot);
var parent = (key.Mapping, key.Parent);
if (!_siblingNames.TryGetValue(parent, out var names)) return;
foreach (var item in entry.Snapshot.Items)
{
var name = item.Metadata.BrowseName; var old = names[name];
if (old.Count == 1) names.Remove(name); else names[name] = (old.Address, old.Count - 1);
}
if (names.Count == 0) _siblingNames.Remove(parent);
}
private void AddParent(ParentKey key, ProjectedParentSnapshot page)
{
RemoveParent(key);
var entry = new ParentEntry(page) { Sweep = _parentSweep.AddLast(key) }; _parents.Add(key, entry);
_retainedBytes = checked(_retainedBytes + PageBytes(key, page));
var parent = (key.Mapping, key.Parent);
if (!_siblingNames.TryGetValue(parent, out var names)) _siblingNames[parent] = names = new(StringComparer.Ordinal);
foreach (var item in page.Items)
{
names.TryGetValue(item.Metadata.BrowseName, out var old);
names[item.Metadata.BrowseName] = (item.OriginMetadata.View.Address, old.Count + 1);
}
}
private void RemoveNode((DataRealm Realm, string Id) key)
{
if (!_nodes.Remove(key, out var node)) return;
_nodeSweep.Remove(node.Sweep!); node.Sweep = null;
if (node.Pins > 0) { node.Retired = true; _retiredPinned.Add(node); }
else { _retainedBytes -= Bytes(node.Proof); ChangeMappingCount(node, -1); }
}
private void AddNode((DataRealm Realm, string Id) key, ProjectedNodeProof proof)
{
RemoveNode(key);
var node = new NodeEntry(proof) { Sweep = _nodeSweep.AddLast(key) }; _nodes.Add(key, node);
_retainedBytes = checked(_retainedBytes + Bytes(proof)); ChangeMappingCount(node, 1);
}
// Fixed work per admission. Rotate live entries so repeated capacity pressure reaches idle expired entries.
private void ReclaimExpired()
{
for (var i = 0; i < 64 && _parentSweep.First is { } first; i++)
{
var key = first.Value; var entry = _parents[key];
if (entry.Snapshot.Lease is not { IsValid: true } || entry.Snapshot.LocalAuthority is not { IsActive: true }) RemoveParent(key);
else { _parentSweep.RemoveFirst(); _parentSweep.AddLast(first); }
if (_parentSweep.Count <= i + 1) break;
}
for (var i = 0; i < 64 && _nodeSweep.First is { } first; i++)
{
var key = first.Value; var node = _nodes[key];
if (!Valid(node.Proof)) RemoveNode(key);
else { _nodeSweep.RemoveFirst(); _nodeSweep.AddLast(first); }
if (_nodeSweep.Count <= i + 1) break;
}
}
/// <summary>Captures a generation before asynchronous work begins.</summary>
public long CaptureGeneration(string mappingId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(mappingId);
lock (_sync)
{
if (_mappingGenerations.TryGetValue(mappingId, out var value)) return value;
if (_mappingGenerations.Count >= _maxParents) throw new InvalidOperationException("Projection mapping capacity exhausted.");
var generation = checked(++_nextGeneration);
_mappingGenerations.Add(mappingId, generation); return generation;
}
}
internal bool IsCurrentGeneration(string mappingId, long generation)
{
lock (_sync) return !_saturated && _mappingGenerations.TryGetValue(mappingId, out var current) && current == generation;
}
private static bool SamePlacement(MappedNamespaceSubject left, MappedNamespaceSubject right) =>
left.View == right.View && left.Serving == right.Serving && left.AllowedOperations == right.AllowedOperations &&
left.WriteThrough == right.WriteThrough && left.Scope.Kind == right.Scope.Kind &&
string.Equals(left.Scope.ClusterId, right.Scope.ClusterId, StringComparison.OrdinalIgnoreCase) &&
left.Scope.Segments.SequenceEqual(right.Scope.Segments, StringComparer.Ordinal) &&
left.LocalAncestry.SequenceEqual(right.LocalAncestry, StringComparer.OrdinalIgnoreCase);
private bool Usable(ProjectedBrowseRequest request) => request.ConfiguredCapability is { } capability
? capability.Matches(request.MappingId, request.Parent, null) : request.Caller is not null && _policy is not null && _policy.IsCallerUsable(request.Caller);
private bool Allowed(ProjectedBrowseRequest request, ProjectedNodeProof proof) => Valid(proof) &&
(request.ConfiguredCapability is { } capability ? capability.Matches(request.MappingId, proof.Metadata.View, proof.Resolver.LocalAuthority) :
_policy is not null && request.Caller is not null && _policy.AuthorizeMapped(request.Caller, OpcUaOperation.Browse, proof.Metadata.View, proof.Subject.Serving, proof.Subject, proof.Resolver, proof.Lease));
private static ProjectedParentSnapshot Empty(ProjectionPageStatus status, long generation = 0) => new(status, [], false, null, generation);
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request)
{
ArgumentNullException.ThrowIfNull(request);
lock (_sync)
{
if (_saturated) return Empty(ProjectionPageStatus.Unavailable);
if (_unavailable.TryGetValue(Parent(request.MappingId, request.Parent), out var unavailable)) return Empty(ProjectionPageStatus.Unavailable, unavailable);
if (!_parents.TryGetValue(Key(request), out var entry)) return Empty(ProjectionPageStatus.Pending);
if (_policy is null || !Usable(request) ||
entry.Snapshot.Lease is not { IsValid: true } || entry.Snapshot.LocalAuthority is not { IsActive: true } local ||
local.AuthorityEpoch != _policy.AuthorityEpoch ||
(request.ConfiguredCapability is null && request.Caller.CredentialExpiresUtc is { } expiry && expiry <= Clock.GetUtcNow())) return Empty(ProjectionPageStatus.Unavailable);
if (entry.Snapshot.ParentProof is not { } parent || parent.Metadata.View != request.Parent || !Allowed(request, parent) ||
entry.Snapshot.Items.Any(item => !Allowed(request, item))) return Empty(ProjectionPageStatus.Unavailable);
return entry.Snapshot;
}
}
private sealed class ParentGuard(ProjectedCatalogCache owner, ParentKey key, object version,
ProjectedBrowseRequest request, ProjectedNodeProof parent, IDataAuthorizationLease lease,
IDataMappedCatalogAuthority local, long generation, long bytes) : IProjectedPageGuard
{
public long RetainedBytes => bytes;
public bool IsCurrent
{
get
{
try
{
lock (owner._sync)
{
if (owner._saturated || !owner._parents.TryGetValue(key, out var entry) || !ReferenceEquals(entry.Version, version) ||
!owner._mappingGenerations.TryGetValue(key.Mapping, out var current) || current != generation ||
owner._unavailable.ContainsKey((key.Mapping, key.Parent)) || owner._policy is null ||
local.AuthorityEpoch != owner._policy.AuthorityEpoch || !owner.Usable(request) || !owner.Allowed(request, parent)) return false;
// External authorization can change authority while it executes. The fast source fence is last.
return local.IsActive && local.AuthorityEpoch == owner._policy.AuthorityEpoch && lease.IsValid &&
owner._parents.TryGetValue(key, out var final) && ReferenceEquals(final.Version, version) &&
owner._mappingGenerations.TryGetValue(key.Mapping, out var latest) && latest == generation;
}
}
catch (Exception) { return false; }
}
}
}
public IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected)
{
lock (_sync)
{
var key = Key(request);
if (!_parents.TryGetValue(key, out var entry) || !ReferenceEquals(entry.Snapshot, expected) ||
expected.Status != ProjectionPageStatus.Ready || expected.ParentProof is not { } parent ||
expected.Lease is not { } lease || expected.LocalAuthority is not { } local) return null;
return new ParentGuard(this, key, entry.Version, request, parent, lease, local, expected.Generation,
checked(1024L + KeyBytes(key) + Bytes(parent)));
}
}
/// <summary>Publishes a fully verified page; collisions, inactive leases and capacity fail closed.</summary>
public bool TryPublish(ProjectedBrowseRequest request, ProjectedParentSnapshot page) => TryPublish(request, page, null, out _);
internal bool TryPublish(ProjectedBrowseRequest request, ProjectedParentSnapshot page,
Func<(bool Success, string? Cursor)>? commitCursor, out ProjectedParentSnapshot? committed, int maximumMappingNodes = int.MaxValue)
{
committed = null;
ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(page);
if (page.Status != ProjectionPageStatus.Ready || page.Generation <= 0 || _policy is null || page.Lease is not { IsValid: true } ||
page.LocalAuthority is not { IsActive: true } local || local.AuthorityEpoch != _policy.AuthorityEpoch || !Usable(request) ||
page.ParentProof is not { } parent || parent.Metadata.View != request.Parent || parent.Generation != page.Generation ||
!ReferenceEquals(parent.Resolver.LocalAuthority, local) || parent.Lease.Serving != page.Lease.Serving || !Allowed(request, parent)) return false;
ProjectedNodeProof[] items;
try { items = page.Items.Select(Freeze).ToArray(); parent = Freeze(parent); }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NullReferenceException) { return false; }
var indexedItems = IsValueNode(parent.Metadata) ? items.Append(parent).ToArray() : items;
lock (_sync)
{
if (_saturated || !_mappingGenerations.TryGetValue(request.MappingId, out var mappingGeneration) || mappingGeneration != page.Generation ||
!page.Lease.IsValid || !local.IsActive || !Usable(request) || !Allowed(request, parent) ||
items.Any(item => item.Generation != page.Generation || item.Lease.Serving != page.Lease.Serving ||
!ReferenceEquals(item.Resolver.LocalAuthority, local) || !Allowed(request, item)) ||
indexedItems.Select(item => (item.Metadata.View.Realm, item.LocalIdentifier)).Distinct().Count() != indexedItems.Length) return false;
var key = Key(request);
var estimatedPage = KeyBytes(key) + Bytes(parent) + items.Sum(Bytes);
_mappingNodeCounts.TryGetValue(request.MappingId, out var initialMappingCount);
if ((!_parents.ContainsKey(key) && _parents.Count >= _maxParents) || _nodes.Count + _retiredPinned.Count + indexedItems.Length > _maxNodes ||
_retainedBytes + estimatedPage > _maxBytes || (long)initialMappingCount + indexedItems.Length > maximumMappingNodes) ReclaimExpired();
if (!_parents.ContainsKey(key) && _parents.Count >= _maxParents) return false;
if (_nodes.Count + _retiredPinned.Count + indexedItems.Count(item => !_nodes.TryGetValue((item.Metadata.View.Realm, item.LocalIdentifier), out var prior) || prior.Pins > 0) > _maxNodes) return false;
_mappingNodeCounts.TryGetValue(request.MappingId, out var retainedForMapping);
var additions = indexedItems.Count(item => !_nodes.TryGetValue((item.Metadata.View.Realm, item.LocalIdentifier), out var existing) || existing.Pins > 0);
if ((long)retainedForMapping + additions > maximumMappingNodes) return false;
var oldPageBytes = _parents.TryGetValue(key, out var previousPage) ? KeyBytes(key) + (previousPage.Snapshot.ParentProof is { } oldParent ? Bytes(oldParent) : 0) + previousPage.Snapshot.Items.Sum(Bytes) : 0;
var nodeDelta = indexedItems.Sum(item => _nodes.TryGetValue((item.Metadata.View.Realm, item.LocalIdentifier), out var current)
? current.Pins > 0 ? Bytes(item) : Bytes(item) - Bytes(current.Proof) : Bytes(item));
if (_retainedBytes - oldPageBytes + KeyBytes(key) + Bytes(parent) + items.Sum(Bytes) + nodeDelta > _maxBytes) return false;
// Each mapped parent has an index across its pages, so unrelated pages do no work here.
if (_siblingNames.TryGetValue(Parent(request.MappingId, request.Parent), out var siblingNames))
foreach (var item in items)
if (siblingNames.TryGetValue(item.Metadata.BrowseName, out var old) && old.Address != item.OriginMetadata.View.Address) return false;
foreach (var item in indexedItems)
if (_nodes.TryGetValue((item.Metadata.View.Realm, item.LocalIdentifier), out var existing) &&
(existing.Retired || !SamePlacement(existing.Proof.Subject, item.Subject))) return false;
var cursor = commitCursor is null ? (true, page.Continuation) : commitCursor();
if (!cursor.Item1) return false;
foreach (var item in indexedItems)
{
var nodeKey = (item.Metadata.View.Realm, item.LocalIdentifier);
AddNode(nodeKey, item);
}
_unavailable.Remove(Parent(request.MappingId, request.Parent));
committed = page with { Items = Array.AsReadOnly(items), ParentProof = parent, Continuation = cursor.Item2 };
AddParent(key, committed);
return true;
}
}
public void MarkUnavailable(string mappingId, DataView parent)
{
long generation;
lock (_sync)
{
generation = checked(++_nextGeneration);
if (!_mappingGenerations.ContainsKey(mappingId) && _mappingGenerations.Count >= _maxParents) _saturated = true;
else _mappingGenerations[mappingId] = generation;
if (!_unavailable.ContainsKey(Parent(mappingId, parent)) && _unavailable.Count >= _maxParents) _saturated = true;
else _unavailable[Parent(mappingId, parent)] = generation;
foreach (var key in _parents.Keys.Where(k => string.Equals(k.Mapping, mappingId, StringComparison.OrdinalIgnoreCase)).ToArray()) RemoveParent(key);
foreach (var key in _nodes.Where(p => string.Equals(p.Value.Proof.Subject.View.MappingId, mappingId, StringComparison.OrdinalIgnoreCase)).Select(p => p.Key).ToArray())
{
RemoveNode(key);
}
}
Invalidated?.Invoke(mappingId, generation);
}
/// <summary>Reclaims a removed mapping after its current generation has been fenced.</summary>
public void ForgetMapping(string mappingId)
{
lock (_sync)
{
_mappingGenerations.Remove(mappingId);
foreach (var key in _unavailable.Keys.Where(key => string.Equals(key.Mapping, mappingId, StringComparison.OrdinalIgnoreCase)).ToArray()) _unavailable.Remove(key);
}
}
/// <summary>Checks one exact committed proof without retaining or scanning its original page.</summary>
internal bool IsCurrentProof(ProjectedNodeProof proof)
{
lock (_sync) return _nodes.TryGetValue((proof.Metadata.View.Realm, proof.LocalIdentifier), out var entry) &&
!entry.Retired && ReferenceEquals(entry.Proof, proof) && Valid(proof);
}
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof)
{
lock (_sync)
{
if (_nodes.TryGetValue((realm, localId), out var entry) && !entry.Retired && Valid(entry.Proof)) { proof = entry.Proof; return true; }
proof = null; return false;
}
}
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin)
{
lock (_sync)
{
if (!_nodes.TryGetValue((realm, localId), out var entry) || entry.Retired || !Valid(entry.Proof)) { pin = null; return false; }
entry.Pins++; pin = new Pin(this, entry); return true;
}
}
private sealed class Pin(ProjectedCatalogCache owner, NodeEntry entry) : IDisposable
{
private int _disposed;
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
lock (owner._sync)
{
entry.Pins--;
if (entry.Pins == 0 && entry.Retired)
{
var key = (entry.Proof.Metadata.View.Realm, entry.Proof.LocalIdentifier);
if (owner._nodes.TryGetValue(key, out var current) && ReferenceEquals(current, entry)) owner.RemoveNode(key);
if (owner._retiredPinned.Remove(entry)) { owner._retainedBytes -= Bytes(entry.Proof); owner.ChangeMappingCount(entry, -1); }
}
}
}
}
}
@@ -0,0 +1,118 @@
using Akka.Actor;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
internal sealed class ProjectedByteQuota(long maximum)
{
private readonly object _gate = new();
private long _used;
internal bool TryAdjust(long delta)
{
lock (_gate)
{
if (delta > 0 && delta > maximum - _used) return false;
_used += delta;
return true;
}
}
}
/// <summary>Byte-charged coalescing storage; actor messages carry only a wake, never values.</summary>
internal sealed class ProjectedCoalescingMailbox<T> : IDisposable where T : class
{
private readonly object _gate = new();
private readonly IActorRef _target;
private readonly Func<ProjectedCoalescingMailbox<T>, object> _wake;
private readonly long _maximumBytes;
private readonly int _maximumItems;
private readonly ProjectedByteQuota? _sharedQuota;
private readonly bool _retainDelivered;
private readonly Dictionary<string, (T Value, long Charge)> _delivered = new(StringComparer.Ordinal);
private readonly Dictionary<string, (T Value, long Charge)> _queued = new(StringComparer.Ordinal);
private long _bytes;
private bool _notified, _disposed;
internal ProjectedCoalescingMailbox(IActorRef target, Func<ProjectedCoalescingMailbox<T>, object> wake, long maximumBytes, int maximumItems, ProjectedByteQuota? sharedQuota = null, bool retainDelivered = false)
{ _target = target; _wake = wake; _maximumBytes = maximumBytes; _maximumItems = maximumItems; _sharedQuota = sharedQuota; _retainDelivered = retainDelivered; }
internal bool TryOffer(IReadOnlyList<(string Key, T Value, long Charge)> items)
{
bool notify;
lock (_gate)
{
if (_disposed || items.Any(x => x.Charge <= 0) || items.Select(x => x.Key).Distinct(StringComparer.Ordinal).Count() != items.Count) return false;
long next = _bytes;
var added = 0;
try
{
foreach (var item in items)
{
if (_queued.TryGetValue(item.Key, out var old)) next = checked(next - old.Charge);
else added++;
next = checked(next + item.Charge);
}
}
catch (OverflowException) { return false; }
if (next > _maximumBytes || _queued.Count + added > _maximumItems ||
_sharedQuota is not null && !_sharedQuota.TryAdjust(next - _bytes)) return false;
foreach (var item in items) _queued[item.Key] = (item.Value, item.Charge);
_bytes = next; notify = !_notified; _notified = true;
}
if (notify) _target.Tell(_wake(this));
return true;
}
internal Batch Take()
{
lock (_gate)
{
_notified = false;
var items = _queued.ToArray(); _queued.Clear();
return new Batch(this, items);
}
}
private void Release(KeyValuePair<string, (T Value, long Charge)>[] items)
{
lock (_gate)
{
long released = 0;
foreach (var item in items)
{
if (_retainDelivered && !_disposed)
{
if (_delivered.TryGetValue(item.Key, out var prior)) released += prior.Charge;
_delivered[item.Key] = item.Value;
}
else released += item.Value.Charge;
}
_bytes -= released; _sharedQuota?.TryAdjust(-released);
}
}
internal sealed class Batch : IDisposable
{
private readonly ProjectedCoalescingMailbox<T> _owner;
private readonly KeyValuePair<string, (T Value, long Charge)>[] _items;
private int _done;
internal Batch(ProjectedCoalescingMailbox<T> owner, KeyValuePair<string, (T Value, long Charge)>[] items)
{ _owner = owner; _items = items; Items = items.Select(x => x.Value.Value).ToArray(); }
internal IReadOnlyList<T> Items { get; }
public void Dispose() { if (Interlocked.Exchange(ref _done, 1) == 0) _owner.Release(_items); }
}
internal void Clear()
{
lock (_gate)
{
var released = _queued.Values.Sum(x => x.Charge);
_bytes -= released; _sharedQuota?.TryAdjust(-released); _queued.Clear();
}
}
public void Dispose()
{
lock (_gate)
{
if (_disposed) return;
_disposed = true; var released = _queued.Values.Sum(x => x.Charge) + _delivered.Values.Sum(x => x.Charge);
_bytes -= released; _sharedQuota?.TryAdjust(-released); _queued.Clear(); _delivered.Clear();
}
}
}
@@ -0,0 +1,732 @@
using Opc.Ua;
using System.Threading.Channels;
using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Finite ownership limits for mapped access and its physical work.</summary>
public sealed record ProjectedDataAccessLimits(int MaxDemands, int MaxUnaryOperations, long MaxUnaryBytes, int MaxStreams);
/// <summary>Admission and asynchronous transport for projected SDK access.</summary>
public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
{
private readonly object _sync = new();
public TimeProvider Clock { get; }
private readonly IFederatedProjectionCatalog _catalog;
private readonly IProjectedNodeLookup _nodes;
private readonly Func<string, string?> _connectionForMapping;
private readonly DataOperationPolicy _policy;
private readonly ProjectedDataAccessLimits _limits;
private readonly IGrpcDataAdapterConnectionSource _connections;
private readonly IProjectedValuePublisher _publisher;
private readonly Func<(bool Allowed, long Generation)> _localWriteRole;
private readonly Dictionary<SourceKey, SourceState> _sources = new();
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, HashSet<SourceKey>> _sourcesByMapping = new(StringComparer.OrdinalIgnoreCase);
private readonly object _sourceRetirementGate = new();
private readonly LinkedList<SourceKey> _sourceSweep = new();
private readonly Dictionary<SourceKey, LinkedListNode<SourceKey>> _sourceSweepNodes = new();
private readonly Dictionary<string, long> _pendingSourceRetirement = new(StringComparer.OrdinalIgnoreCase);
private bool _sourceRetirementRunning;
internal Action? BeforeSourceRetirementForTests { get; set; }
internal int PendingSourceRetirementsForTests { get { lock (_sourceRetirementGate) return _pendingSourceRetirement.Count; } }
private int _unaryCount;
private long _unaryBytes;
private readonly Dictionary<CohortKey, Cohort> _cohorts = new();
private readonly Dictionary<Demand, Cohort> _demandCohorts = new();
private readonly HashSet<Demand> _demands = [];
private readonly Dictionary<(DataRealm Realm, string Identifier), int> _demandCounts = new();
private bool _disposed;
public ProjectedDataAccess(IFederatedProjectionCatalog catalog, IProjectedNodeLookup nodes,
IGrpcDataAdapterConnectionSource connections, Func<string, string?> connectionForMapping,
DataOperationPolicy policy, IProjectedValuePublisher publisher, TimeProvider clock, ProjectedDataAccessLimits limits,
Func<(bool Allowed, long Generation)>? localWriteRole = null)
{
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); _nodes = nodes ?? throw new ArgumentNullException(nameof(nodes));
_connections = connections ?? throw new ArgumentNullException(nameof(connections)); _connectionForMapping = connectionForMapping ?? throw new ArgumentNullException(nameof(connectionForMapping));
_policy = policy ?? throw new ArgumentNullException(nameof(policy)); _publisher = publisher ?? throw new ArgumentNullException(nameof(publisher)); Clock = clock ?? throw new ArgumentNullException(nameof(clock));
_limits = limits ?? throw new ArgumentNullException(nameof(limits));
_localWriteRole = localWriteRole ?? (() => (true, 1));
if (limits.MaxDemands <= 0 || limits.MaxUnaryOperations <= 0 || limits.MaxUnaryBytes <= 0 || limits.MaxStreams <= 0) throw new ArgumentOutOfRangeException(nameof(limits));
_catalog.Invalidated += OnCatalogInvalidated;
}
private static bool MetadataMatches(DataMetadata left, DataMetadata right) =>
left.Dimensions.SequenceEqual(right.Dimensions) && (left with { Dimensions = right.Dimensions }) == right;
private static ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue EncodeValue(DataMetadata metadata, object? value)
{
if (value is null) return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.Null();
if (metadata.ValueKind == DataValueKind.Array)
{
if (metadata.ValueRank != 1 || metadata.Dimensions.Count != 1 || metadata.ArrayElementKind is not { } kind || value is not Array array || array.Rank != 1 ||
(metadata.Dimensions[0] != 0 && metadata.Dimensions[0] != array.Length)) throw new ArgumentException("Incompatible array shape.");
var values = new object[array.Length];
for (var i = 0; i < values.Length; i++)
{
var item = array.GetValue(i) ?? throw new ArgumentException("Null array element.");
values[i] = kind == DataValueKind.Timestamp && item is DateTime time ? new DateTimeOffset(time.ToUniversalTime()) : item;
}
return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromArray(kind, values, [array.Length]);
}
if (metadata.ValueKind == DataValueKind.Bytes && value is byte[] bytes)
return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromBytes(bytes);
if (metadata.ValueKind == DataValueKind.Timestamp && value is DateTime timestamp) value = new DateTimeOffset(timestamp.ToUniversalTime());
return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(metadata.ValueKind, value);
}
private static object? DecodeValue(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue value, DataMetadata metadata)
{
if (value.Kind == DataValueKind.Null) return null;
if (value.Kind != metadata.ValueKind) throw new ArgumentException("Value kind does not match metadata.");
if (value.Kind == DataValueKind.Bytes) return value.GetBytes().ToArray();
if (value.Kind != DataValueKind.Array) return value.GetScalar();
if (metadata.ValueRank != 1 || metadata.ArrayElementKind != value.ArrayElementKind || value.Dimensions is not { Count: 1 } dims ||
metadata.Dimensions.Count != 1 || (metadata.Dimensions[0] != 0 && metadata.Dimensions[0] != dims[0])) throw new ArgumentException("Incompatible array shape.");
var items = value.GetArray();
return value.ArrayElementKind switch
{
DataValueKind.Boolean => items.Cast<bool>().ToArray(), DataValueKind.Int8 => items.Cast<sbyte>().ToArray(),
DataValueKind.UInt8 => items.Cast<byte>().ToArray(), DataValueKind.Int16 => items.Cast<short>().ToArray(),
DataValueKind.UInt16 => items.Cast<ushort>().ToArray(), DataValueKind.Int32 => items.Cast<int>().ToArray(),
DataValueKind.UInt32 => items.Cast<uint>().ToArray(), DataValueKind.Int64 => items.Cast<long>().ToArray(),
DataValueKind.UInt64 => items.Cast<ulong>().ToArray(), DataValueKind.Float => items.Cast<float>().ToArray(),
DataValueKind.Double => items.Cast<double>().ToArray(), DataValueKind.String => items.Cast<string>().ToArray(),
DataValueKind.Timestamp => items.Cast<DateTimeOffset>().Select(x => x.UtcDateTime).ToArray(),
DataValueKind.Guid => items.Cast<Guid>().ToArray(), _ => throw new ArgumentException("Unsupported array element kind.")
};
}
public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand)
{
demand = null;
if (caller is null || operation is not (DataOperations.Browse or DataOperations.Read or DataOperations.Write or DataOperations.Subscribe)) return false;
try
{
if (!_nodes.TryResolve(nodeId, out var definition) || definition is null || !definition.AuthorityIsCurrent() ||
!_catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var proof) || proof is null ||
proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) ||
((operation is DataOperations.Read or DataOperations.Subscribe) && proof.MaximumSampleAge <= TimeSpan.Zero) ||
proof.Metadata.View.MappingId is not { } mapping || proof.Lease.Serving.ServingGeneration <= 0 ||
_connectionForMapping(mapping) is not { Length: > 0 } connectionId) return false;
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
var localRole = operation == DataOperations.Write ? _localWriteRole() : (Allowed: true, Generation: 1L);
if (!localRole.Allowed || localRole.Generation <= 0) return false;
var op = Operation(operation);
if (!_policy.AuthorizeMapped(identity, op, proof.Metadata.View, proof.Lease.Serving, proof.Subject, proof.Resolver, proof.Lease) ||
!definition.Lifetime.TryPin(out var nodePin) || nodePin is null) return false;
if (!_catalog.TryPinProjected(definition.Realm, definition.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); return false; }
var candidate = new Demand(this, nodeId, definition, proof, identity, operation, pin, nodePin, connectionId, localRole.Generation, null);
lock (_sync)
{
if (_disposed || _demands.Count >= _limits.MaxDemands) { pin.Dispose(); nodePin.Dispose(); return false; }
_demands.Add(candidate);
var key = (candidate.Realm, candidate.LocalIdentifier);
_demandCounts.TryGetValue(key, out var count); _demandCounts[key] = checked(count + 1);
}
if (!candidate.IsValid) { candidate.Dispose(); return false; }
demand = candidate; return true;
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
}
internal bool TryAcquireConfigured(NodeId nodeId, ConfiguredProjectionCapability capability, out IProjectedDemandLease? demand)
{
demand = null;
try
{
if (!_nodes.TryResolve(nodeId, out var definition) || definition is null || !definition.AuthorityIsCurrent() ||
!_catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var proof) || proof is null ||
proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) || proof.MaximumSampleAge <= TimeSpan.Zero ||
proof.Metadata.View.MappingId is not { } mapping || proof.Lease.Serving.ServingGeneration <= 0 ||
(proof.Subject.AllowedOperations & DataOperations.Subscribe) == 0 || !capability.Matches(mapping, proof.Metadata.View, proof.Resolver.LocalAuthority) ||
_connectionForMapping(mapping) is not { Length: > 0 } connectionId || !definition.Lifetime.TryPin(out var nodePin) || nodePin is null) return false;
if (!_catalog.TryPinProjected(definition.Realm, definition.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); return false; }
var candidate = new Demand(this, nodeId, definition, proof, null, DataOperations.Subscribe, pin, nodePin, connectionId, 1, capability);
lock (_sync)
{
if (_disposed || _demands.Count >= _limits.MaxDemands) { pin.Dispose(); nodePin.Dispose(); return false; }
_demands.Add(candidate); var key = (candidate.Realm, candidate.LocalIdentifier);
_demandCounts.TryGetValue(key, out var count); _demandCounts[key] = checked(count + 1);
}
if (!candidate.IsValid) { candidate.Dispose(); return false; }
demand = candidate; return true;
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
}
internal async ValueTask DisposeConfiguredAsync(IProjectedDemandLease lease)
{
lease.Dispose();
if (lease is Demand demand) await demand.Completion.ConfigureAwait(false);
}
public bool HasLiveDemand(DataRealm realm, string localIdentifier) { lock (_sync) return _demandCounts.ContainsKey((realm, localIdentifier)); }
private static OpcUaOperation Operation(DataOperations operation) => operation switch
{
DataOperations.Browse => OpcUaOperation.Browse,
DataOperations.Read => OpcUaOperation.Read,
DataOperations.Write => OpcUaOperation.WriteOperate,
DataOperations.Subscribe => OpcUaOperation.CreateMonitoredItems,
_ => throw new ArgumentOutOfRangeException(nameof(operation))
};
private sealed class Demand(ProjectedDataAccess owner, NodeId nodeId, ProjectedVariableDefinition definition,
ProjectedNodeProof proof, DataCallerIdentity? caller, DataOperations operation, IDisposable pin, IProjectedNodePin nodePin, string connectionId, long writeRoleGeneration, ConfiguredProjectionCapability? configured) : IProjectedDemandLease
{
private int _disposed;
private int _holds;
private bool _cleaned;
private readonly TaskCompletionSource _completed = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly CancellationTokenSource _stop = new();
internal ProjectedNodeProof Proof => proof;
internal ProjectedVariableDefinition Definition => definition;
internal DataOperations RequestedOperation => operation;
internal bool Disposed => Volatile.Read(ref _disposed) != 0;
internal bool TryHold() { lock (owner._sync) { if (_disposed != 0) return false; _holds++; return true; } }
internal void ReleaseHold() { lock (owner._sync) { _holds--; if (_disposed != 0 && _holds == 0) Cleanup(); } }
private void Cleanup()
{
if (_cleaned) return;
_cleaned = true;
pin.Dispose(); nodePin.Dispose(); owner._demands.Remove(this);
var key = (Realm, LocalIdentifier); var count = owner._demandCounts[key];
if (count == 1) owner._demandCounts.Remove(key); else owner._demandCounts[key] = count - 1;
_completed.TrySetResult();
}
internal Task Completion => _completed.Task;
public TimeSpan MaximumSampleAge => proof.MaximumSampleAge;
public DataView OriginView => proof.OriginMetadata.View;
public DataRealm Realm => definition.Realm;
public string LocalIdentifier => definition.LocalIdentifier;
public long ProjectionGeneration => proof.Generation;
public ServingIdentity Serving => proof.Lease.Serving;
public CancellationToken CancellationToken => _stop.Token;
public bool IsValid
{
get
{
if (Volatile.Read(ref _disposed) != 0) return false;
try
{
var role = operation == DataOperations.Write ? owner._localWriteRole() : (Allowed: true, Generation: 1L);
return role.Allowed && role.Generation == writeRoleGeneration && role.Generation > 0 && nodePin.IsValid && definition.AuthorityIsCurrent() && owner._nodes.TryResolve(nodeId, out var now) && now is not null && ReferenceEquals(now.Lifetime, definition.Lifetime) && now.ProjectionGeneration == definition.ProjectionGeneration && now.Metadata.View == definition.Metadata.View &&
owner._catalog.TryResolveProjected(Realm, LocalIdentifier, out var current) && ReferenceEquals(current, proof) &&
string.Equals(owner._connectionForMapping(proof.Metadata.View.MappingId!), connectionId, StringComparison.OrdinalIgnoreCase) &&
(configured is not null ? configured.Matches(proof.Metadata.View.MappingId!, proof.Metadata.View, proof.Resolver.LocalAuthority) && (proof.Subject.AllowedOperations & DataOperations.Subscribe) != 0 :
caller is not null && owner._policy.AuthorizeMapped(caller, Operation(operation), proof.Metadata.View, Serving, proof.Subject, proof.Resolver, proof.Lease)) &&
Volatile.Read(ref _disposed) == 0;
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
}
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
_ = _stop.CancelAsync();
lock (owner._sync)
{
if (owner._demandCohorts.TryGetValue(this, out var cohort)) cohort.Remove(this);
if (_holds == 0) Cleanup();
}
}
}
private sealed record SourceKey(string Connection, DataView View, ServingIdentity Serving, long Generation);
private sealed class SourceState : IProjectedSamplePublicationProof
{
private readonly ProjectedDataAccess _owner; private readonly SourceKey _key; private readonly ProjectedValueRoute _route;
private ProjectedNodeProof? _proof; private ProjectedVariableDefinition? _definition; private IDisposable? _pin; private IProjectedNodePin? _nodePin;
internal readonly object Gate = new(); internal long LastVersion;
internal string MappingId { get; }
internal SourceState(ProjectedDataAccess owner, SourceKey key, ProjectedNodeProof proof, ProjectedVariableDefinition definition,
IDisposable pin, IProjectedNodePin nodePin, ProjectedValueRoute route)
{ _owner = owner; _key = key; _proof = proof; _definition = definition; _pin = pin; _nodePin = nodePin; _route = route; MappingId = proof.Metadata.View.MappingId!; }
internal ProjectedValueRoute Route => _route;
public TimeProvider Clock => _owner.Clock;
public bool IsValid
{
get
{
lock (Gate)
{
var proof = _proof; var definition = _definition;
try { return proof is not null && definition is not null && _nodePin is { IsValid: true } && definition.AuthorityIsCurrent() && proof.Lease.IsValid &&
_owner._catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var now) && ReferenceEquals(now, proof) &&
string.Equals(_owner._connectionForMapping(proof.Metadata.View.MappingId!), _key.Connection, StringComparison.OrdinalIgnoreCase); }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
}
}
}
public void Invalidate()
{
IDisposable? pin; IProjectedNodePin? nodePin;
lock (Gate)
{
if (_proof is null) return;
_proof = null; _definition = null; pin = _pin; _pin = null; nodePin = _nodePin; _nodePin = null;
}
try { _owner._publisher.Retire(_route); }
catch (Exception) { }
finally { nodePin?.Dispose(); pin?.Dispose(); }
}
}
private bool RemoveSourceLocked(SourceKey key, out SourceState? source)
{
if (!_sources.Remove(key, out source)) return false;
if (_sourceSweepNodes.Remove(key, out var sweep)) _sourceSweep.Remove(sweep);
if (_sourcesByMapping.TryGetValue(source.MappingId, out var keys))
{
keys.Remove(key);
if (keys.Count == 0)
{
_sourcesByMapping.TryRemove(source.MappingId, out _);
lock (_sourceRetirementGate) _pendingSourceRetirement.Remove(source.MappingId);
}
}
return true;
}
private void OnCatalogInvalidated(string mapping, long generation)
{
// Mapping activation may hold its own lock. Never acquire the data-access
// lock on this callback; publication is allowed to consult mapping authority.
lock (_sourceRetirementGate)
{
if (Volatile.Read(ref _disposed) || !_sourcesByMapping.ContainsKey(mapping)) return;
_pendingSourceRetirement[mapping] = generation;
if (_sourceRetirementRunning) return;
_sourceRetirementRunning = true; _ = Task.Run(RetireInvalidatedSources);
}
}
private void RetireInvalidatedSources()
{
BeforeSourceRetirementForTests?.Invoke();
while (true)
{
SourceState[] retired;
KeyValuePair<string, long> item;
lock (_sourceRetirementGate)
{
if (_pendingSourceRetirement.Count == 0) { _sourceRetirementRunning = false; return; }
item = _pendingSourceRetirement.First(); _pendingSourceRetirement.Remove(item.Key);
}
lock (_sync)
{
var list = new List<SourceState>();
if (_sourcesByMapping.TryGetValue(item.Key, out var keys))
foreach (var key in keys.Where(key => key.Generation != item.Value).ToArray())
if (RemoveSourceLocked(key, out var state) && state is not null) list.Add(state);
retired = list.ToArray();
}
foreach (var source in retired) source.Invalidate();
}
}
private SourceState? GetSource(Demand demand, string connection)
{
var proof = demand.Proof; var key = new SourceKey(connection.ToUpperInvariant(), demand.OriginView, demand.Serving, demand.ProjectionGeneration);
lock (_sync)
{
if (_sources.TryGetValue(key, out var existing))
{
if (existing.IsValid) return existing;
RemoveSourceLocked(key, out _); existing.Invalidate();
}
if (_sources.Count >= _limits.MaxDemands)
{
var count = Math.Min(16, _sourceSweep.Count);
for (var i = 0; i < count && _sourceSweep.First is { } first; i++)
{
var sourceKey = first.Value; var state = _sources[sourceKey];
if (!state.IsValid) { RemoveSourceLocked(sourceKey, out _); state.Invalidate(); }
else { _sourceSweep.RemoveFirst(); _sourceSweep.AddLast(first); }
}
}
if (_sources.Count >= _limits.MaxDemands || !demand.Definition.Lifetime.TryPin(out var nodePin) || nodePin is null) return null;
if (!_catalog.TryPinProjected(demand.Realm, demand.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); return null; }
var route = new ProjectedValueRoute("grpc-data:" + connection, ProjectedDataIds.DependencyReference(demand.Realm, demand.LocalIdentifier),
demand.Realm, demand.LocalIdentifier, demand.ProjectionGeneration, demand.Serving, Guid.NewGuid());
var source = new SourceState(this, key, proof, demand.Definition, pin, nodePin, route);
if (!source.IsValid || !_publisher.TryBind(route)) { source.Invalidate(); return null; }
_sources.Add(key, source); _sourceSweepNodes.Add(key, _sourceSweep.AddLast(key));
if (!_sourcesByMapping.TryGetValue(source.MappingId, out var keys)) _sourcesByMapping[source.MappingId] = keys = new();
keys.Add(key);
// Attach before the final authority check: invalidation either observes this
// bucket or is detected here, so no source can strand its physical pins.
if (!source.IsValid) { RemoveSourceLocked(key, out _); source.Invalidate(); return null; }
return source;
}
}
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;
try { budget.Validate(); } catch (ArgumentException) { return false; }
var elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp());
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return false;
lock (_sync)
{
if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || budget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) return false;
_unaryCount++; _unaryBytes += budget.MaxBytes;
}
_ = Task.Run(() => ReadCoreAsync(item, budget, requestStartedTimestamp)); return true;
}
private async Task ReadCoreAsync(Demand demand, DataBudget budget, long started)
{
IGrpcDataAdapterConnectionLease? connection = null;
try
{
var remaining = budget.Timeout - Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (remaining <= TimeSpan.Zero || !demand.IsValid) return;
var connectionId = _connectionForMapping(demand.Proof.Metadata.View.MappingId!);
if (string.IsNullOrWhiteSpace(connectionId)) return;
using var timeout = new CancellationTokenSource(remaining, Clock);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, demand.CancellationToken);
connection = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false);
if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) || connection.CancellationToken.IsCancellationRequested || !demand.IsValid) return;
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
var result = await connection.Connection.ReadAsync(new DataReadRequest([new ReadItem("0", demand.OriginView, null)], budget with { Timeout = remaining }), route.Token).ConfigureAwait(false);
try
{
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 != demand.Serving || sample.Version <= 0 || !demand.IsValid || route.IsCancellationRequested) return;
result[0].AgeBounds.Validate();
if (!result[0].AgeBounds.IsFresh(demand.MaximumSampleAge)) return;
if (sample.Value.EstimatedRetainedBytes > budget.MaxBytes) return;
var payload = DecodeValue(sample.Value, demand.Proof.OriginMetadata);
var snapshot = new DataValueSnapshot(payload, sample.StatusCode, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime);
var received = Clock.GetTimestamp(); var source = GetSource(demand, connectionId);
if (source is null) return;
lock (source.Gate)
{
if (!demand.IsValid || !source.IsValid || sample.Version <= source.LastVersion) return;
if (_publisher.TryPublish([new(source.Route, snapshot, result[0].AgeBounds, received, source, true, demand.MaximumSampleAge)])) source.LastVersion = sample.Version;
else source.Invalidate();
}
}
finally { foreach (var item in result) item.Dispose(); }
}
catch (Exception) { }
finally
{
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
finally { demand.Dispose(); demand.ReleaseHold(); lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } }
}
}
public async Task<DataWriteOutcome> WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget,
long requestStartedTimestamp, CancellationToken cancellationToken)
{
var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, StatusCodes.BadNotConnected.Code, null);
var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, StatusCodes.BadTimeout.Code, null);
if (demand is not Demand item || item.RequestedOperation != DataOperations.Write || !item.IsValid || budget is null || cancellationToken.IsCancellationRequested) return rejected;
ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue owned;
try
{
budget.Validate();
owned = EncodeValue(item.Proof.OriginMetadata, value);
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return rejected; }
var elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp());
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || owned.EstimatedRetainedBytes > budget.MaxBytes) { owned.Dispose(); return rejected; }
lock (_sync)
{
if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || budget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) { owned.Dispose(); return rejected; }
_unaryCount++; _unaryBytes += budget.MaxBytes;
}
var task = Task.Run(() => WriteCoreAsync(item, owned, budget, requestStartedTimestamp, cancellationToken));
try { return await task.WaitAsync(budget.Timeout - elapsed, Clock, cancellationToken).ConfigureAwait(false); }
catch (OperationCanceledException) { return unknown; }
catch (TimeoutException) { return unknown; }
}
private async Task<DataWriteOutcome> WriteCoreAsync(Demand demand, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue value, DataBudget budget, long started, CancellationToken callerStop)
{
var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, StatusCodes.BadNotConnected.Code, null);
var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, StatusCodes.BadTimeout.Code, null);
IGrpcDataAdapterConnectionLease? connection = null; var dispatched = false;
try
{
var remaining = budget.Timeout - Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (remaining <= TimeSpan.Zero || !demand.IsValid || callerStop.IsCancellationRequested) return rejected;
var connectionId = _connectionForMapping(demand.Proof.Metadata.View.MappingId!);
if (string.IsNullOrWhiteSpace(connectionId)) return rejected;
using var timeout = new CancellationTokenSource(remaining, Clock);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, callerStop, demand.CancellationToken);
connection = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false);
if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) || connection.CancellationToken.IsCancellationRequested || !demand.IsValid) return rejected;
remaining = budget.Timeout - Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (remaining <= TimeSpan.Zero || linked.IsCancellationRequested) return rejected;
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
var correlation = Guid.NewGuid().ToString("N");
var item = new WriteItem(correlation, Guid.NewGuid().ToString("N"), demand.OriginView, value,
demand.Proof.OriginMetadata.CatalogRevision, demand.Serving.Incarnation, remaining, demand.Serving.ServingGeneration);
dispatched = true;
var results = await connection.Connection.WriteAsync(new WriteBatch([item], budget with { Timeout = remaining }), route.Token).ConfigureAwait(false);
if (results.Count != 1 || results[0].CorrelationId != correlation) return unknown;
return results[0].Outcome;
}
catch (Exception) { return dispatched ? unknown : rejected; }
finally
{
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
finally { value.Dispose(); demand.ReleaseHold(); lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } }
}
}
private sealed record CohortKey(string Connection, ServingIdentity Serving, TimeSpan Interval);
public bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval)
{
if (demand is not Demand item || item.RequestedOperation != DataOperations.Subscribe || publishingInterval <= TimeSpan.Zero || !item.IsValid) return false;
var connection = _connectionForMapping(item.Proof.Metadata.View.MappingId!);
if (string.IsNullOrWhiteSpace(connection)) return false;
var key = new CohortKey(connection.ToUpperInvariant(), item.Serving, publishingInterval);
lock (_sync)
{
if (_disposed || _demandCohorts.ContainsKey(item)) return false;
var created = false;
if (!_cohorts.TryGetValue(key, out var cohort))
{
if (_cohorts.Count >= _limits.MaxStreams) return false;
cohort = new Cohort(this, key, connection); _cohorts.Add(key, cohort); created = true;
}
if (cohort.Closing || !item.TryHold()) { if (created) _cohorts.Remove(key); return false; }
_demandCohorts.Add(item, cohort);
if (!cohort.Add(item)) { _demandCohorts.Remove(item); item.ReleaseHold(); if (created) _cohorts.Remove(key); return false; }
cohort.Start(); return true;
}
}
private sealed class Cohort
{
private abstract record Event;
private sealed record AddEvent(Demand Demand) : Event;
private sealed record RemoveEvent(Demand Demand) : Event;
private sealed record FrameEvent(DataSubscriptionFrame Frame, long Bytes) : Event;
private sealed record EndEvent : Event;
private sealed class Registration(Demand demand, string id)
{ internal readonly Demand Demand = demand; internal readonly string Id = id; internal DataItemHandle? Handle; internal bool Removed; }
private readonly ProjectedDataAccess _owner;
private readonly CohortKey _key;
private readonly string _connectionId;
private readonly Channel<Event> _events;
private readonly CancellationTokenSource _stop = new();
private readonly Dictionary<Demand, Registration> _registrations = new();
private readonly Dictionary<string, Registration> _byId = new(StringComparer.Ordinal);
private readonly Dictionary<DataItemHandle, Registration> _byHandle = new();
private readonly Dictionary<string, Registration> _removing = new(StringComparer.Ordinal);
private readonly string _id = Guid.NewGuid().ToString("N");
private const long Epoch = 1;
private int _started, _closing, _restart;
private long _sequence;
private long _frameBytes;
internal bool Closing => Volatile.Read(ref _closing) != 0;
internal Cohort(ProjectedDataAccess owner, CohortKey key, string connectionId)
{
_owner = owner; _key = key; _connectionId = connectionId;
_events = Channel.CreateBounded<Event>(new BoundedChannelOptions(Math.Clamp(owner._limits.MaxDemands * 2, 4, 128))
{ SingleReader = true, FullMode = BoundedChannelFullMode.Wait });
}
internal bool Add(Demand demand) => _events.Writer.TryWrite(new AddEvent(demand));
internal void Remove(Demand demand) { if (!_events.Writer.TryWrite(new RemoveEvent(demand))) Stop(); }
internal void Start() { if (Interlocked.Exchange(ref _started, 1) == 0) _ = Task.Run(RunAsync); }
internal void Stop() { if (Interlocked.Exchange(ref _closing, 1) == 0) _ = _stop.CancelAsync(); }
internal bool Restart()
{
if (Volatile.Read(ref _restart) != 0) return true;
if (Closing) return false;
Interlocked.Exchange(ref _restart, 1); Stop(); return true;
}
private async Task PumpAsync(IDataSubscription stream)
{
try
{
await foreach (var frame in stream.ReadAllAsync(_stop.Token).ConfigureAwait(false))
{
var bytes = frame is DataSubscriptionValues values ? checked(512L + values.Items.Sum(x => x.Sample.Value.EstimatedRetainedBytes)) : 512L;
if (bytes > _owner._limits.MaxUnaryBytes || Interlocked.Add(ref _frameBytes, bytes) > _owner._limits.MaxUnaryBytes)
{ Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); break; }
try { await _events.Writer.WriteAsync(new FrameEvent(frame, bytes), _stop.Token).ConfigureAwait(false); }
catch { Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); throw; }
}
}
catch (Exception) { }
finally { _events.Writer.TryWrite(new EndEvent()); }
}
private DataSubscriptionItem Item(Registration registration) => new(registration.Id, registration.Demand.OriginView,
new DataSubscriptionSettings(_key.Interval, _key.Interval, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataChangeTrigger.StatusValueTimestamp, null));
private async Task RunAsync()
{
IGrpcDataAdapterConnectionLease? connection = null; IDataSubscription? stream = null; Task? pump = null;
var opened = false; var inSnapshot = false; long snapshotBytes = 0;
var pending = new List<(Registration Registration, ProjectedValueUpdate Update, long Version)>();
try
{
connection = await _owner._connections.AcquireAsync(_connectionId, _stop.Token).ConfigureAwait(false);
if (connection is null || !ReferenceEquals(connection.Connection.Clock, _owner.Clock) || connection.CancellationToken.IsCancellationRequested) return;
using var route = CancellationTokenSource.CreateLinkedTokenSource(_stop.Token, connection.CancellationToken);
stream = await connection.Connection.SubscribeAsync(route.Token).ConfigureAwait(false);
if (stream is not IDataSubscriptionProvenance provenance || provenance.Serving != _key.Serving) return;
pump = PumpAsync(stream);
await foreach (var message in _events.Reader.ReadAllAsync(route.Token).ConfigureAwait(false))
{
if (message is AddEvent add)
{
if (!add.Demand.IsValid) continue;
var registration = new Registration(add.Demand, Guid.NewGuid().ToString("N"));
_registrations[add.Demand] = registration; _byId[registration.Id] = registration;
DataSubscriptionCommand command = !opened
? new OpenSubscription(_id, Epoch, Guid.NewGuid().ToString("N"), TimeSpan.FromSeconds(5), [Item(registration)], false, TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, _owner._limits.MaxUnaryBytes))
: new AddSubscriptionItems(_id, Epoch, Guid.NewGuid().ToString("N"), TimeSpan.FromSeconds(5), [Item(registration)]);
await stream.SendAsync(command, route.Token).ConfigureAwait(false); opened = true;
}
else if (message is RemoveEvent remove)
{
if (_registrations.TryGetValue(remove.Demand, out var registration))
{
registration.Removed = true;
if (registration.Handle is { } handle)
{
var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration;
await stream.SendAsync(new RemoveSubscriptionItems(_id, Epoch, commandId, TimeSpan.FromSeconds(5), [handle]), route.Token).ConfigureAwait(false);
}
}
if (_registrations.Values.All(x => x.Removed)) break;
}
else if (message is EndEvent) break;
else if (message is FrameEvent delivered)
{
var frame = delivered.Frame;
try
{
if (frame.SubscriptionId != _id || frame.StreamEpoch != Epoch || frame.Sequence <= _sequence) break;
_sequence = frame.Sequence;
if (frame is DataSubscriptionAck ack)
{
if (_removing.Remove(ack.CommandId, out var removed))
{
if (ack.Items.Count != 1 || ack.Items[0].Status != DataItemStatus.Good || ack.Items[0].Handle != removed.Handle || ack.Items[0].ClientItemId != removed.Id) { Stop(); continue; }
_registrations.Remove(removed.Demand); _byId.Remove(removed.Id);
if (removed.Handle is { } removedHandle) _byHandle.Remove(removedHandle);
SourceState? retiredSource = null;
lock (_owner._sync)
{
_owner._demandCohorts.Remove(removed.Demand);
if (!_registrations.Values.Any(x => !x.Removed && x.Demand.OriginView == removed.Demand.OriginView && x.Demand.ProjectionGeneration == removed.Demand.ProjectionGeneration))
{
var sourceKey = new SourceKey(_key.Connection, removed.Demand.OriginView, _key.Serving, removed.Demand.ProjectionGeneration);
_owner.RemoveSourceLocked(sourceKey, out retiredSource);
}
}
retiredSource?.Invalidate();
removed.Demand.ReleaseHold();
}
else foreach (var response in ack.Items)
{
if (!_byId.TryGetValue(response.ClientItemId, out var registration) || response.Status != DataItemStatus.Good || response.Handle is null) { Stop(); break; }
registration.Handle = response.Handle; _byHandle[response.Handle] = registration;
if (registration.Removed)
{
var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration;
await stream.SendAsync(new RemoveSubscriptionItems(_id, Epoch, commandId, TimeSpan.FromSeconds(5), [response.Handle]), route.Token).ConfigureAwait(false);
}
}
}
else if (frame is DataSubscriptionControl control)
{
if (control.CatalogEpoch != _key.Serving.CatalogEpoch || control.AuthorityEpoch != _key.Serving.AuthorityEpoch) break;
if (control.Kind == DataStreamControlKind.SnapshotBegin) { inSnapshot = true; pending.Clear(); snapshotBytes = 0; }
else if (control.Kind == DataStreamControlKind.SnapshotEnd && inSnapshot)
{
foreach (var item in pending) Publish(item.Registration, item.Update with { IsCompleteSnapshot = true }, item.Version);
pending.Clear(); snapshotBytes = 0; inSnapshot = false;
}
else if (control.Kind is DataStreamControlKind.Reset or DataStreamControlKind.CatalogInvalidated or DataStreamControlKind.AuthorityInvalidated) break;
}
else if (frame is DataSubscriptionValues values)
{
foreach (var item in values.Items)
{
if (!_byHandle.TryGetValue(item.Handle, out var registration) || registration.Removed || !registration.Demand.IsValid ||
item.Sample.Serving != _key.Serving || item.Sample.Version <= 0 || item.Readiness != DataReadiness.Ready ||
!item.AgeBounds.IsFresh(registration.Demand.MaximumSampleAge) || item.Sample.Value.EstimatedRetainedBytes > _owner._limits.MaxUnaryBytes)
{ Stop(); break; }
var source = _owner.GetSource(registration.Demand, _connectionId); if (source is null) { Stop(); break; }
var sample = item.Sample;
var payload = DecodeValue(sample.Value, registration.Demand.Proof.OriginMetadata);
var update = new ProjectedValueUpdate(source.Route, new DataValueSnapshot(payload, sample.StatusCode, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime),
item.AgeBounds, _owner.Clock.GetTimestamp(), source, false, registration.Demand.MaximumSampleAge);
if (inSnapshot)
{
snapshotBytes = checked(snapshotBytes + sample.Value.EstimatedRetainedBytes + 512);
if (pending.Count >= _owner._limits.MaxDemands || snapshotBytes > _owner._limits.MaxUnaryBytes) { Stop(); break; }
pending.Add((registration, update, sample.Version));
}
else Publish(registration, update, sample.Version);
}
}
}
finally { Interlocked.Add(ref _frameBytes, -delivered.Bytes); (frame as IDisposable)?.Dispose(); }
}
}
}
catch (Exception) { }
finally
{
Stop();
try { if (stream is not null) await stream.DisposeAsync().ConfigureAwait(false); }
catch (Exception) { }
try { if (pump is not null) await pump.ConfigureAwait(false); }
catch (Exception) { }
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
catch (Exception) { }
while (_events.Reader.TryRead(out var remaining)) if (remaining is FrameEvent f) { Interlocked.Add(ref _frameBytes, -f.Bytes); (f.Frame as IDisposable)?.Dispose(); }
Demand[] owned; var transferred = new HashSet<Demand>(); var retired = new List<SourceState>();
lock (_owner._sync)
{
owned = _owner._demandCohorts.Where(x => ReferenceEquals(x.Value, this)).Select(x => x.Key).ToArray();
foreach (var item in owned) _owner._demandCohorts.Remove(item);
if (_owner._cohorts.TryGetValue(_key, out var current) && ReferenceEquals(current, this)) _owner._cohorts.Remove(_key);
foreach (var item in owned)
{
var sourceKey = new SourceKey(_key.Connection, item.OriginView, _key.Serving, item.ProjectionGeneration);
if (_owner.RemoveSourceLocked(sourceKey, out var state) && state is not null) retired.Add(state);
}
}
foreach (var source in retired) source.Invalidate();
lock (_owner._sync)
{
if (Volatile.Read(ref _restart) != 0 && !_owner._disposed)
{
var eligible = owned.Where(d => !d.Disposed).ToArray();
if (eligible.Length > 0 && !_owner._cohorts.ContainsKey(_key) && _owner._cohorts.Count < _owner._limits.MaxStreams)
{
var replacement = new Cohort(_owner, _key, _connectionId); _owner._cohorts.Add(_key, replacement);
foreach (var demand in eligible)
if (replacement.Add(demand)) { _owner._demandCohorts[demand] = replacement; transferred.Add(demand); }
if (transferred.Count > 0) replacement.Start(); else _owner._cohorts.Remove(_key);
}
}
}
foreach (var item in owned) if (!transferred.Contains(item)) { item.Dispose(); item.ReleaseHold(); }
_stop.Dispose();
}
}
private void Publish(Registration registration, ProjectedValueUpdate update, long version)
{
if (!registration.Demand.IsValid || update.SourceProof is not SourceState source) return;
lock (source.Gate)
{
if (!source.IsValid || version <= source.LastVersion) return;
if (_owner._publisher.TryPublish([update])) source.LastVersion = version; else source.Invalidate();
}
}
}
public bool RequestFreshSnapshot(IProjectedDemandLease demand)
{
if (demand is not Demand item || item.RequestedOperation != DataOperations.Subscribe || !item.IsValid) return false;
lock (_sync) return !_disposed && _demandCohorts.TryGetValue(item, out var cohort) && cohort.Restart();
}
public void Dispose()
{
_catalog.Invalidated -= OnCatalogInvalidated;
Demand[] demands;
lock (_sync) { if (_disposed) return; _disposed = true; demands = _demands.ToArray(); }
foreach (var demand in demands) demand.Dispose();
Cohort[] cohorts;
lock (_sync) cohorts = _cohorts.Values.ToArray();
foreach (var cohort in cohorts) cohort.Stop();
SourceState[] sources;
lock (_sync) { sources = _sources.Values.ToArray(); _sources.Clear(); _sourcesByMapping.Clear(); _sourceSweep.Clear(); _sourceSweepNodes.Clear(); lock (_sourceRetirementGate) _pendingSourceRetirement.Clear(); }
foreach (var source in sources) source.Invalidate();
}
}
@@ -0,0 +1,249 @@
using System.Text.Json;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>A mapped root placed under an applied local catalog parent.</summary>
public sealed record ProjectedMappingPlacement(RemoteNamespaceMapping Mapping, DataView Parent, DataView Anchor,
NodeScope Scope, IReadOnlyList<string> LocalAncestry, IDataMappedCatalogAuthority Authority);
/// <summary>Owns mapping placements tied to one activated catalog attempt.</summary>
public sealed class ProjectedMappingDeploymentRuntime : IDisposable
{
private readonly object _gate = new();
private readonly LocalCatalogCoordinator _coordinator;
private readonly RemoteNamespaceResolver _resolver;
private CatalogAttempt? _attempt;
private RemoteNamespaceMapping[] _staged = [];
private DataConnection[] _connections = [];
private IReadOnlyList<ProjectedMappingPlacement> _active = Array.Empty<ProjectedMappingPlacement>();
private Dictionary<string, ProjectedMappingPlacement> _byMapping = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, ConfiguredProjectionCapability> _configuredCapabilities = new(StringComparer.OrdinalIgnoreCase);
private object _configuredStamp = new();
private bool _disposed;
public ProjectedMappingDeploymentRuntime(LocalCatalogCoordinator coordinator, RemoteNamespaceResolver resolver)
{
_coordinator = coordinator ?? throw new ArgumentNullException(nameof(coordinator));
_resolver = resolver ?? throw new ArgumentNullException(nameof(resolver));
_coordinator.AttachProjectedMappings(this);
}
private static T Copy<T>(T value) => JsonSerializer.Deserialize<T>(JsonSerializer.SerializeToUtf8Bytes(value))!;
private long _placementCopiesForTests;
internal long PlacementCopiesForTests => Interlocked.Read(ref _placementCopiesForTests);
private IReadOnlyList<ProjectedMappingPlacement> CopyPlacements(IReadOnlyList<ProjectedMappingPlacement> source)
{
Interlocked.Add(ref _placementCopiesForTests, source.Count);
return Array.AsReadOnly(source.Select(x => x with { Mapping = Copy(x.Mapping) }).ToArray());
}
// Mint only from an exact currently published placement. The capability guard is
// deliberately lock-free: cache validation can run under the cache lock while a
// mapping transition holds _gate and calls into that cache.
internal bool TryAcquireConfiguredCapability(string mappingId, DataRealm realm,
out ConfiguredProjectionCapability? capability, out ProjectedMappingPlacement? placement)
{
capability = null;
placement = null;
lock (_gate)
{
if (_disposed || _attempt is null || !_byMapping.TryGetValue(mappingId, out var original) ||
!original.Authority.IsActive || original.Mapping.Realm != realm || original.Mapping.RemoteRealm != realm ||
!original.Mapping.Enabled ||
(original.Mapping.AllowedOperations & (DataOperations.Browse | DataOperations.Subscribe)) !=
(DataOperations.Browse | DataOperations.Subscribe)) return false;
var catalog = _coordinator.MappingCatalog(_attempt);
if (catalog is null || !ReferenceEquals(catalog.MappingAuthority, original.Authority)) return false;
var published = Volatile.Read(ref _active);
if (!published.Any(item => ReferenceEquals(item, original))) return false;
placement = CopyPlacements([original])[0];
if (!_configuredCapabilities.TryGetValue(original.Mapping.RemoteNamespaceMappingId, out capability))
{
var stamp = Volatile.Read(ref _configuredStamp);
capability = new ConfiguredProjectionCapability(original.Mapping.RemoteNamespaceMappingId, original.Mapping.Revision,
original.Mapping.Realm, original.Mapping.AllowedOperations, original.Authority,
() => ReferenceEquals(Volatile.Read(ref _configuredStamp), stamp));
_configuredCapabilities.Add(original.Mapping.RemoteNamespaceMappingId, capability);
}
return true;
}
}
internal bool IsCurrentPlacement(ProjectedMappingPlacement placement)
{
lock (_gate)
{
if (_disposed || _attempt is null || !placement.Authority.IsActive ||
!_byMapping.TryGetValue(placement.Mapping.RemoteNamespaceMappingId, out var current) ||
!ReferenceEquals(current.Authority, placement.Authority) ||
current.Mapping.RemoteNamespaceMappingId != placement.Mapping.RemoteNamespaceMappingId ||
current.Mapping.Revision != placement.Mapping.Revision ||
!string.Equals(current.Mapping.DataConnectionId, placement.Mapping.DataConnectionId, StringComparison.OrdinalIgnoreCase) ||
current.Parent != placement.Parent || current.Anchor != placement.Anchor) return false;
var catalog = _coordinator.MappingCatalog(_attempt);
return catalog is not null && ReferenceEquals(catalog.MappingAuthority, current.Authority);
}
}
public IReadOnlyList<ProjectedMappingPlacement> Active
{
get
{
lock (_gate)
return _active.All(x => x.Authority.IsActive) ? CopyPlacements(_active) : Array.Empty<ProjectedMappingPlacement>();
}
}
public event Action<IReadOnlyList<ProjectedMappingPlacement>>? Changed;
/// <summary>Resolve a mapping only while its original activated authority remains current.</summary>
public bool TryGetConnectionId(string mappingId, out string? connectionId)
{
lock (_gate)
{
connectionId = null;
if (_disposed || _attempt is null || !_byMapping.TryGetValue(mappingId, out var placement) || !placement.Authority.IsActive)
return false;
var current = _coordinator.MappingCatalog(_attempt);
if (current is null || !ReferenceEquals(current.MappingAuthority, placement.Authority)) return false;
connectionId = placement.Mapping.DataConnectionId;
return true;
}
}
public void Stage(CatalogAttempt attempt, IReadOnlyList<RemoteNamespaceMapping> mappings, IReadOnlyList<DataConnection> connections)
{
ArgumentNullException.ThrowIfNull(attempt);
ArgumentNullException.ThrowIfNull(mappings);
ArgumentNullException.ThrowIfNull(connections);
var frozenMappings = mappings.Select(Copy).ToArray();
var frozenConnections = connections.Select(Copy).ToArray();
lock (_gate)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!ReferenceEquals(attempt, _attempt)) return;
_staged = frozenMappings;
_connections = frozenConnections;
}
}
internal void AttemptBegan(CatalogAttempt attempt)
{
bool changed;
lock (_gate)
{
if (_disposed || _attempt is not null && attempt.Epoch <= _attempt.Epoch) return;
_attempt = attempt;
Volatile.Write(ref _configuredStamp, new object());
_configuredCapabilities.Clear();
_staged = []; _connections = [];
changed = _active.Count != 0;
Volatile.Write(ref _active, Array.Empty<ProjectedMappingPlacement>());
_byMapping.Clear();
_resolver.ApplyMappings([]);
}
if (changed) Notify([]);
}
internal void AttemptCompleted(CatalogAttempt attempt, bool completed)
{
IReadOnlyList<ProjectedMappingPlacement> published;
lock (_gate)
{
if (_disposed || !ReferenceEquals(_attempt, attempt)) return;
Volatile.Write(ref _configuredStamp, new object());
_configuredCapabilities.Clear();
var catalog = completed ? _coordinator.MappingCatalog(attempt) : null;
if (catalog is null || !catalog.IsActive)
{
_resolver.ApplyMappings([]);
Volatile.Write(ref _active, Array.Empty<ProjectedMappingPlacement>());
}
else
{
try
{
var placements = Build(catalog, _staged, _connections);
var bindings = placements.Select(p => new ProjectedMappingBinding(p.Mapping, p.Anchor, p.Scope,
p.LocalAncestry, p.Authority, (_, _) => false)).ToArray();
_resolver.ApplyMappings(bindings);
var current = _coordinator.MappingCatalog(attempt);
if (current is null || !ReferenceEquals(current.MappingAuthority, catalog.MappingAuthority) || !catalog.IsActive)
throw new InvalidOperationException("Catalog attempt changed during projection activation.");
Volatile.Write(ref _active, Array.AsReadOnly(placements));
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OverflowException)
{
_resolver.ApplyMappings([]);
Volatile.Write(ref _active, Array.Empty<ProjectedMappingPlacement>());
}
}
_byMapping = _active.ToDictionary(x => x.Mapping.RemoteNamespaceMappingId, StringComparer.OrdinalIgnoreCase);
published = CopyPlacements(_active);
}
Notify(published);
}
private static ProjectedMappingPlacement[] Build(LocalExportCatalog catalog, IReadOnlyList<RemoteNamespaceMapping> mappings,
IReadOnlyList<DataConnection> connections)
{
var placements = new List<ProjectedMappingPlacement>();
foreach (var mapping in mappings.Where(x => x.Enabled))
{
var parentMatches = catalog.Nodes.Where(x => x.EntityKind == mapping.LocalParentKind &&
string.Equals(x.EntityId, mapping.LocalParentId, StringComparison.OrdinalIgnoreCase) && x.Metadata.View.Realm == mapping.Realm).ToArray();
var connectionMatches = connections.Where(x => x.Enabled && string.Equals(x.DataConnectionId, mapping.DataConnectionId, StringComparison.OrdinalIgnoreCase) &&
string.Equals(x.ClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase)).ToArray();
if (parentMatches.Length != 1 || connectionMatches.Length != 1 || string.IsNullOrWhiteSpace(connectionMatches[0].ExpectedClusterId) ||
!string.Equals(mapping.ClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(mapping.BranchName) ||
mapping.BranchName.Contains('/') || mapping.BranchName.Contains('\\') || mapping.Realm != mapping.RemoteRealm ||
catalog.Children(parentMatches[0]).Any(x => string.Equals(x.Metadata.BrowseName, mapping.BranchName, StringComparison.OrdinalIgnoreCase)) ||
placements.Any(x => x.Parent == parentMatches[0].Metadata.View && string.Equals(x.Mapping.BranchName, mapping.BranchName, StringComparison.OrdinalIgnoreCase)))
throw new ArgumentException("Invalid or colliding mapping placement.");
var parent = parentMatches[0];
var ancestry = new List<string>();
var cursor = parent;
var seen = new HashSet<DataView>();
while (true)
{
if (!seen.Add(cursor.Metadata.View)) throw new ArgumentException("Catalog parent cycle.");
ancestry.Add(cursor.EntityId);
if (cursor.Parent is null) break;
if (!catalog.TryResolve(cursor.Parent, out cursor!)) throw new ArgumentException("Catalog parent missing.");
}
ancestry.Reverse();
var segments = Array.AsReadOnly(parent.Scope.Segments.Concat([mapping.BranchName]).ToArray());
var scope = parent.Scope with { Segments = segments };
var address = new DataAddress(connectionMatches[0].ExpectedClusterId, mapping.RemoteNamespaceUri,
mapping.RemoteIdentifierKind, mapping.RemoteIdentifier);
var anchor = new DataView(address, mapping.Realm, mapping.RemoteNamespaceMappingId, mapping.Revision, string.Join('/', segments));
anchor.Validate();
placements.Add(new(mapping, parent.Metadata.View, anchor, scope, Array.AsReadOnly(ancestry.ToArray()), catalog.MappingAuthority));
}
return placements.ToArray();
}
private void Notify(IReadOnlyList<ProjectedMappingPlacement> placements)
{
var handlers = Changed;
if (handlers is null) return;
foreach (Action<IReadOnlyList<ProjectedMappingPlacement>> handler in handlers.GetInvocationList())
try { handler(CopyPlacements(placements)); } catch (Exception) { }
}
public void Dispose()
{
lock (_gate)
{
if (_disposed) return;
_disposed = true;
Volatile.Write(ref _configuredStamp, new object());
_configuredCapabilities.Clear();
Volatile.Write(ref _active, Array.Empty<ProjectedMappingPlacement>());
_byMapping.Clear();
_resolver.ApplyMappings([]);
_coordinator.DetachProjectedMappings(this);
}
Notify([]);
}
}
@@ -0,0 +1,132 @@
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Prepares bounded remote pages and hands them to the local atomic publication boundary.</summary>
public sealed class ProjectedNamespaceApplier : IDisposable
{
private readonly IFederatedProjectionCatalog _catalog;
private readonly IProjectedNamespacePageSink _sink;
private readonly SemaphoreSlim _slots;
private readonly CancellationTokenSource _stop = new();
private int _disposed;
public ProjectedNamespaceApplier(IFederatedProjectionCatalog catalog, IProjectedNamespacePageSink sink, int maxConcurrent)
{
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
_sink = sink ?? throw new ArgumentNullException(nameof(sink));
if (maxConcurrent <= 0) throw new ArgumentOutOfRangeException(nameof(maxConcurrent));
_slots = new(maxConcurrent, maxConcurrent);
}
private sealed class CommitState(long generation, ServingIdentity serving)
{
private int _aborted;
internal long Generation => generation;
internal ServingIdentity Serving => serving;
internal bool Aborted => Volatile.Read(ref _aborted) != 0;
internal void Abort() => Interlocked.Exchange(ref _aborted, 1);
}
// This object deliberately owns one frozen item and small shared control only. A bound method
// must never capture the preparation frame, its siblings, request, linked CTS or cursor owner.
private sealed class ItemGuard : IProjectedRetainedAuthority
{
internal readonly ProjectedNodeProof Proof;
private readonly CommitState _state;
private readonly CancellationToken _stop;
internal ItemGuard(ProjectedNodeProof proof, CommitState state, CancellationToken stop)
{
Proof = proof with
{
Metadata = proof.Metadata with { Dimensions = Array.AsReadOnly(proof.Metadata.Dimensions.ToArray()) },
OriginMetadata = proof.OriginMetadata with { Dimensions = Array.AsReadOnly(proof.OriginMetadata.Dimensions.ToArray()) },
Subject = proof.Subject with
{
Scope = proof.Subject.Scope with { Segments = Array.AsReadOnly(proof.Subject.Scope.Segments.ToArray()) },
LocalAncestry = Array.AsReadOnly(proof.Subject.LocalAncestry.ToArray())
}
};
_state = state; _stop = stop;
RetainedBytes = checked(2048L + ProjectedProofSize.Estimate(Proof));
}
public long RetainedBytes { get; }
public bool IsCurrent()
{
try
{
return !_state.Aborted && !_stop.IsCancellationRequested && Proof.Generation == _state.Generation &&
Proof.Lease.Serving == _state.Serving && Proof.Resolver.LocalAuthority.IsActive &&
Proof.Resolver.Resolve(Proof.Metadata.View, Proof.Subject).Kind == MappedSubjectResolutionKind.Mapped && Proof.Lease.IsValid;
}
catch (Exception) { return false; }
}
}
public async Task<bool> ApplyPageAsync(ProjectedBrowseRequest request, NodeId exactParent, CancellationToken cancellationToken) =>
await ApplyPageResultAsync(request, exactParent, cancellationToken).ConfigureAwait(false) == ProjectionPageStatus.Ready;
public async Task<ProjectionPageStatus> ApplyPageResultAsync(ProjectedBrowseRequest request, NodeId exactParent, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
if (Volatile.Read(ref _disposed) != 0 || !_slots.Wait(0)) return ProjectionPageStatus.Unavailable;
try
{
request.Budget.Validate();
var elapsed = _catalog.Clock.GetElapsedTime(request.RequestStartedTimestamp, _catalog.Clock.GetTimestamp());
var remaining = request.Budget.Timeout - elapsed;
if (elapsed < TimeSpan.Zero || remaining <= TimeSpan.Zero) return ProjectionPageStatus.Unavailable;
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _stop.Token);
linked.CancelAfter(remaining);
using var prepared = await _catalog.PreparePageAsync(request, linked.Token).ConfigureAwait(false);
var page = prepared.Snapshot;
if (page.Status != ProjectionPageStatus.Ready) return page.Status;
if (page.Generation <= 0 || page.Lease is not { IsValid: true } pageLease || page.LocalAuthority is not { IsActive: true } local ||
page.Items.Count > request.Budget.MaxItems) return ProjectionPageStatus.Unavailable;
var state = new CommitState(page.Generation, pageLease.Serving);
var guards = page.Items.Select(item => new ItemGuard(item, state, _stop.Token)).ToArray();
var root = page.ParentProof is { } parentProof ? new ItemGuard(parentProof, state, _stop.Token) : null;
bool PageCurrent() => Volatile.Read(ref _disposed) == 0 && !linked.IsCancellationRequested &&
!state.Aborted && local.IsActive && pageLease.IsValid;
if (!PageCurrent() || guards.Any(guard => !guard.IsCurrent()) || root is not null && !root.IsCurrent())
return ProjectionPageStatus.Unavailable;
var definitions = guards.Select(guard => new ProjectedVariableDefinition(guard.Proof.Metadata.View.Realm,
guard.Proof.LocalIdentifier, exactParent, guard.Proof.Metadata, guard.Proof.Generation, guard.IsCurrent)).ToArray();
var rootLeaf = root is not null && ProjectedCatalogCache.IsValueNode(root.Proof.Metadata);
if (rootLeaf && (definitions.Length != 0 || !page.Complete)) return ProjectionPageStatus.Unavailable;
var attempted = 0;
var committed = false;
var accepted = false;
bool Commit()
{
if (Interlocked.Exchange(ref attempted, 1) != 0 || !PageCurrent() ||
guards.Any(guard => !guard.IsCurrent()) || root is not null && !root.IsCurrent()) return false;
committed = prepared.TryCommit();
return committed && PageCurrent();
}
try
{
accepted = rootLeaf
? _sink.TryApplyRootLeaf(exactParent, new ProjectedVariableDefinition(root!.Proof.Metadata.View.Realm,
root.Proof.LocalIdentifier, exactParent, root.Proof.Metadata, root.Proof.Generation, root.IsCurrent), Commit)
: _sink.TryApply(exactParent, definitions, Commit);
return accepted && committed && PageCurrent() ? ProjectionPageStatus.Ready : ProjectionPageStatus.Unavailable;
}
// Successful SDK/cache acceptance publishes shared metadata. A later caller timeout
// does not revoke it; its independent lease/deployment guards still fence every use.
finally { if (!accepted || !committed) state.Abort(); }
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested || _stop.IsCancellationRequested) { return ProjectionPageStatus.Unavailable; }
catch (OperationCanceledException) { return ProjectionPageStatus.Unavailable; }
finally { _slots.Release(); }
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 0) _stop.Cancel();
}
}
@@ -0,0 +1,23 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Conservative retained size of one detached projected proof, including both metadata views.</summary>
internal static class ProjectedProofSize
{
internal static long Estimate(ProjectedNodeProof proof) => checked(1024L + Text(proof.LocalIdentifier) +
Metadata(proof.Metadata) + Metadata(proof.OriginMetadata) + View(proof.Subject.View) +
Text(proof.Subject.Scope.ClusterId) + Strings(proof.Subject.Scope.Segments) +
Strings(proof.Subject.LocalAncestry) + Serving(proof.Subject.Serving) + Serving(proof.Lease.Serving));
private static long Text(string? value) => checked(32L + 2L * (value?.Length ?? 0));
private static long Strings(IReadOnlyList<string> values) => checked(64L + 8L * values.Count + values.Sum(Text));
private static long View(DataView view) => checked(128L + Text(view.Subject) + Text(view.MappingId) +
Text(view.Address.OriginClusterId) + Text(view.Address.NamespaceUri) +
Text(view.Address.IdentifierKind) + Text(view.Address.Identifier));
private static long Serving(ServingIdentity? serving) => serving is null ? 0 : checked(128L +
Text(serving.NodeId) + Text(serving.Incarnation) + Text(serving.Role));
private static long Metadata(DataMetadata value) => checked(256L + View(value.View) +
Text(value.BrowseName) + Text(value.NodeKind) + Text(value.StableSourceId) + Text(value.EngineeringUnits) +
64L + 4L * value.Dimensions.Count + Serving(value.Serving));
}
@@ -0,0 +1,287 @@
using System.Collections.ObjectModel;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Trusted placement compiled from an applied mapping and its local catalog authority.</summary>
public sealed record ProjectedMappingBinding(RemoteNamespaceMapping Mapping, DataView LocalAnchor, NodeScope LocalScope,
IReadOnlyList<string> LocalAncestry, IDataMappedCatalogAuthority LocalAuthority, Func<DataView, string, bool> LocalNameOccupied);
/// <summary>Resolves direct peer browse pages without routing origin-owned exports through a projection.</summary>
public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisposable
{
private readonly object _sync = new();
private readonly ProjectedCatalogCache _cache;
private readonly BrowseContinuationRegistry _cursors;
private readonly IGrpcDataAdapterConnectionSource _source;
private readonly DataOperationPolicy _policy;
private readonly int _maxMappings;
private readonly SemaphoreSlim _fetchSlots;
private readonly int _maximumWaiters;
private readonly Func<CancellationToken, Task>? _beforeFetch;
private int _waiterCount;
private sealed record FetchKey(ProjectedBrowseRequest Request, ProjectedMappingBinding Binding);
private sealed class SharedFetch(CancellationTokenSource stop)
{
internal readonly CancellationTokenSource Stop = stop;
internal Task<PreparedPage> Task = null!;
internal int Waiters;
internal readonly TaskCompletionSource Finished = new(TaskCreationOptions.RunContinuationsAsynchronously);
}
private readonly Dictionary<FetchKey, SharedFetch> _fetches = new();
private readonly HashSet<SharedFetch> _physicalJobs = new();
private Dictionary<string, ProjectedMappingBinding> _mappings = new(StringComparer.OrdinalIgnoreCase);
private bool _disposed;
public RemoteNamespaceResolver(ProjectedCatalogCache cache, BrowseContinuationRegistry cursors,
IGrpcDataAdapterConnectionSource source, DataOperationPolicy policy, int maxMappings, int maxConcurrentFetches)
{
_cache = cache ?? throw new ArgumentNullException(nameof(cache)); _cursors = cursors ?? throw new ArgumentNullException(nameof(cursors));
_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);
_maximumWaiters = checked(maxConcurrentFetches * 16);
_cache.Invalidated += OnInvalidated;
}
internal RemoteNamespaceResolver(ProjectedCatalogCache cache, BrowseContinuationRegistry cursors,
IGrpcDataAdapterConnectionSource source, DataOperationPolicy policy, int maxMappings, int maxConcurrentFetches,
Func<CancellationToken, Task>? beforeFetch) : this(cache, cursors, source, policy, maxMappings, maxConcurrentFetches)
{ _beforeFetch = beforeFetch; }
internal int OutstandingPhysicalJobs { get { lock (_sync) return _physicalJobs.Count; } }
internal Task WaitForPhysicalJobsAsync()
{
lock (_sync) return Task.WhenAll(_physicalJobs.Select(x => x.Finished.Task));
}
public TimeProvider Clock => _cache.Clock;
public event Action<string, long>? Invalidated;
private void OnInvalidated(string mappingId, long generation) { _cursors.InvalidateMapping(mappingId); Invalidated?.Invoke(mappingId, generation); }
/// <summary>Installs only an already validated local mapping snapshot.</summary>
public void ApplyMappings(IReadOnlyList<ProjectedMappingBinding> bindings)
{
ArgumentNullException.ThrowIfNull(bindings);
if (bindings.Count > _maxMappings) throw new InvalidOperationException("Mapping capacity exceeded.");
var next = new Dictionary<string, ProjectedMappingBinding>(StringComparer.OrdinalIgnoreCase);
foreach (var binding in bindings)
{
ArgumentNullException.ThrowIfNull(binding);
var mapping = binding.Mapping;
if (!mapping.Enabled || mapping.Revision <= 0 || string.IsNullOrWhiteSpace(mapping.RemoteNamespaceMappingId) ||
string.IsNullOrWhiteSpace(mapping.DataConnectionId) || mapping.Realm != mapping.RemoteRealm || mapping.Realm == DataRealm.Unspecified ||
mapping.MaxProjectionNodes <= 0 || mapping.MaxProjectionDepth <= 0 || mapping.MetadataLeaseMilliseconds <= 0 || mapping.StaleTimeoutMilliseconds <= 0 ||
binding.LocalAnchor.MappingId != mapping.RemoteNamespaceMappingId || binding.LocalAnchor.MappingRevision != mapping.Revision ||
binding.LocalAnchor.Realm != mapping.Realm || binding.LocalAuthority is not { IsActive: true } || binding.LocalNameOccupied is null)
throw new ArgumentException("Invalid projection binding.", nameof(bindings));
var copy = System.Text.Json.JsonSerializer.Deserialize<RemoteNamespaceMapping>(System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(mapping))!;
var frozen = binding with { Mapping = copy, LocalScope = binding.LocalScope with { Segments = Array.AsReadOnly(binding.LocalScope.Segments.ToArray()) },
LocalAncestry = Array.AsReadOnly(binding.LocalAncestry.ToArray()) };
if (!next.TryAdd(copy.RemoteNamespaceMappingId, frozen)) throw new ArgumentException("Duplicate mapping identity.", nameof(bindings));
}
ProjectedMappingBinding[] oldBindings;
lock (_sync)
{
ObjectDisposedException.ThrowIf(_disposed, this);
oldBindings = _mappings.Values.ToArray(); _mappings = next;
}
foreach (var old in oldBindings)
{
_cache.MarkUnavailable(old.Mapping.RemoteNamespaceMappingId, old.LocalAnchor);
if (!next.ContainsKey(old.Mapping.RemoteNamespaceMappingId)) _cache.ForgetMapping(old.Mapping.RemoteNamespaceMappingId);
}
foreach (var item in next.Values) _cache.CaptureGeneration(item.Mapping.RemoteNamespaceMappingId);
}
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => _cache.TryGetParent(request);
public IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) => _cache.CaptureParentGuard(request, expected);
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) => _cache.TryResolveProjected(realm, localId, out proof);
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) => _cache.TryPinProjected(realm, localId, out pin);
public async Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request); request.Budget.Validate(); request.Parent.Validate();
// Continuations remain exclusive reservations; initial requests can share one physical fetch.
if (request.Continuation is not null) return await PrepareCoreAsync(request, cancellationToken).ConfigureAwait(false);
var elapsed = Clock.GetElapsedTime(request.RequestStartedTimestamp, Clock.GetTimestamp());
var remaining = request.Budget.Timeout - elapsed;
if (elapsed < TimeSpan.Zero || remaining <= TimeSpan.Zero) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
SharedFetch work; FetchKey key;
lock (_sync)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!_mappings.TryGetValue(request.MappingId, out var binding) || _waiterCount >= _maximumWaiters)
return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
key = new FetchKey(request with { RequestStartedTimestamp = 0 }, binding);
if (!_fetches.TryGetValue(key, out work!))
{
if (_physicalJobs.Count >= _maximumWaiters) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
work = new SharedFetch(new CancellationTokenSource());
_fetches.Add(key, work); _physicalJobs.Add(work);
var current = work;
current.Task = Task.Run(async () =>
{
if (_beforeFetch is not null) await _beforeFetch(current.Stop.Token).ConfigureAwait(false);
return await PrepareCoreAsync(request, current.Stop.Token).ConfigureAwait(false);
});
}
work.Waiters++; _waiterCount++;
}
try
{
using var timeout = new CancellationTokenSource(remaining, Clock);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token);
var prepared = await work.Task.WaitAsync(linked.Token).ConfigureAwait(false);
return prepared.CloneForWaiter(request);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{ return PreparedPage.Failed(ProjectionPageStatus.Unavailable); }
finally
{
lock (_sync)
{
_waiterCount--; work.Waiters--;
if (work.Waiters == 0)
{
if (_fetches.TryGetValue(key, out var active) && ReferenceEquals(active, work)) _fetches.Remove(key);
if (!work.Task.IsCompleted) _ = work.Stop.CancelAsync();
_ = FinishSharedFetchAsync(work);
}
}
}
}
private async Task FinishSharedFetchAsync(SharedFetch work)
{
try { var page = await work.Task.ConfigureAwait(false); await page.DisposeAndWaitAsync().ConfigureAwait(false); }
catch (Exception) { }
finally
{
work.Stop.Dispose();
lock (_sync) _physicalJobs.Remove(work);
work.Finished.TrySetResult();
}
}
private async Task<PreparedPage> PrepareCoreAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request); request.Budget.Validate(); request.Parent.Validate();
ProjectedMappingBinding binding;
lock (_sync)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!_mappings.TryGetValue(request.MappingId, out binding!)) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
}
if ((request.ConfiguredCapability is { } capability
? !capability.Matches(request.MappingId, request.Parent, binding.LocalAuthority)
: request.Caller is null || !_policy.IsCallerUsable(request.Caller) || !_policy.AuthorizeLocal(request.Caller, OpcUaOperation.Browse, binding.LocalScope)) ||
!binding.LocalAuthority.IsActive || request.Parent.MappingId != binding.Mapping.RemoteNamespaceMappingId ||
request.Parent.MappingRevision != binding.Mapping.Revision || request.Parent.Realm != binding.Mapping.Realm)
return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var elapsed = Clock.GetElapsedTime(request.RequestStartedTimestamp, Clock.GetTimestamp());
var remaining = request.Budget.Timeout - elapsed;
if (elapsed < TimeSpan.Zero || remaining <= TimeSpan.Zero) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
if (!await _fetchSlots.WaitAsync(0, cancellationToken).ConfigureAwait(false)) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
IGrpcDataAdapterConnectionLease? connection = null; PreparedBrowseContinuation? cursor = null; var transferred = false;
try
{
using var timeout = new CancellationTokenSource(remaining, Clock);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token);
connection = await _source.AcquireAsync(binding.Mapping.DataConnectionId, linked.Token).ConfigureAwait(false);
if (connection is null) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
if (!ReferenceEquals(connection.Connection.Clock, Clock) || !string.Equals(connection.Connection.Target.ExpectedClusterId,
request.Parent.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase)) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
var generation = _cache.CaptureGeneration(request.MappingId);
DataMetadata originParent;
ProjectedNodeProof? previousParent = null;
if (request.Parent == binding.LocalAnchor)
{
var originView = new DataView(request.Parent.Address, request.Parent.Realm, null, 0, binding.Mapping.RemoteRootEntityId);
var metadata = await connection.Connection.GetMetadataAsync(new([originView], request.Budget with { Timeout = remaining }), route.Token).ConfigureAwait(false);
if (metadata.Count != 1 || metadata[0].Status != DataItemStatus.Good || metadata[0].Value is not { } root || root.View.Address != originView.Address || root.View.MappingId is not null || root.Serving is null)
return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
originParent = root;
}
else
{
var localId = ProjectedDataIds.Identifier(request.MappingId, request.Parent.Address);
if (!_cache.TryResolveProjected(request.Parent.Realm, localId, out previousParent) || previousParent!.Metadata.View != request.Parent)
return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
originParent = previousParent.OriginMetadata;
}
var serving = originParent.Serving!;
var target = connection.Connection.Target;
if (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 PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var continuationBinding = new BrowseContinuationBinding(request.ConfiguredCapability?.Nonce ?? request.Caller.Principal,
request.ConfiguredCapability is null ? request.Caller.ApiKeyId ?? "" : "configured",
request.ConfiguredCapability is null ? request.Caller.CredentialVersion ?? "" : "configured",
binding.Mapping.RemoteNamespaceMappingId, binding.Mapping.Revision, request.Parent, request.Filter, binding.LocalAuthority.CatalogEpoch,
serving, request.ConfiguredCapability is null ? request.Caller.CredentialExpiresUtc : null);
if (request.Continuation is not null && !_cursors.TryPrepare(request.Continuation, continuationBinding, out cursor))
return PreparedPage.Failed(ProjectionPageStatus.InvalidContinuation);
elapsed = Clock.GetElapsedTime(request.RequestStartedTimestamp, Clock.GetTimestamp()); remaining = request.Budget.Timeout - elapsed;
if (remaining <= TimeSpan.Zero) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var branch = await connection.Connection.BrowseAsync(new BrowseRequest(originParent.View, request.Filter, cursor?.RemoteCursor,
request.Budget with { Timeout = remaining }), route.Token).ConfigureAwait(false);
if (branch.Status != DataItemStatus.Good || branch.Parent != originParent.View || branch.Serving is null || branch.Serving != serving || branch.Lease is null ||
branch.Lease.CatalogEpoch != serving.CatalogEpoch || branch.Lease.AuthorityEpoch != serving.AuthorityEpoch ||
branch.Items.Count > Math.Min(request.Budget.MaxItems, binding.Mapping.MaxProjectionNodes) ||
branch.Complete != (branch.Continuation is null) || connection.CancellationToken.IsCancellationRequested)
return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var maxLease = TimeSpan.FromMilliseconds(binding.Mapping.MetadataLeaseMilliseconds);
var lease = new BoundProjectionLease(new MetadataAuthorityLease(serving, branch.Lease, request.RequestStartedTimestamp, maxLease, TimeSpan.Zero, Clock),
connection.CancellationToken, binding.LocalAuthority, _cache, request.MappingId, generation, () => IsCurrent(binding));
if (!lease.IsValid) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var parentScope = previousParent?.Subject.Scope ?? binding.LocalScope;
var ancestry = previousParent?.Subject.LocalAncestry ?? binding.LocalAncestry;
var mappedParent = originParent with { View = request.Parent, Serving = serving };
var parentSubject = new MappedNamespaceSubject(request.Parent, parentScope, ancestry, serving,
binding.Mapping.AllowedOperations & originParent.AllowedOperations, binding.Mapping.WriteThrough && originParent.Writable);
var parentResolver = new MappedSubjectResolver([parentSubject], serving.CatalogEpoch, binding.LocalAuthority);
var parentProof = new ProjectedNodeProof(ProjectedDataIds.Identifier(request.MappingId, originParent.View.Address), mappedParent, parentSubject, parentResolver, lease, generation, originParent, TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds));
var results = new List<ProjectedNodeProof>(); var seenNames = new HashSet<string>(StringComparer.Ordinal);
foreach (var item in branch.Items)
{
item.Validate();
if (item.Serving != serving || item.View.MappingId is not null || item.View.Realm != request.Parent.Realm ||
item.CatalogRevision != serving.CatalogEpoch || !string.Equals(item.View.Address.OriginClusterId, originParent.View.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase) ||
string.IsNullOrWhiteSpace(item.BrowseName) || item.BrowseName.Contains('/') || !seenNames.Add(item.BrowseName) ||
binding.LocalNameOccupied(request.Parent, item.BrowseName)) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var segments = parentScope.Segments.Concat([item.BrowseName]).ToArray();
if (segments.Length - binding.LocalScope.Segments.Count > binding.Mapping.MaxProjectionDepth) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var localView = item.View with { MappingId = binding.Mapping.RemoteNamespaceMappingId, MappingRevision = binding.Mapping.Revision, Subject = string.Join('/', segments) };
var scope = parentScope with { Segments = Array.AsReadOnly(segments) };
var subject = new MappedNamespaceSubject(localView, scope, ancestry, serving, binding.Mapping.AllowedOperations & item.AllowedOperations, binding.Mapping.WriteThrough && item.Writable);
var resolver = new MappedSubjectResolver([subject], serving.CatalogEpoch, binding.LocalAuthority);
results.Add(new ProjectedNodeProof(ProjectedDataIds.Identifier(request.MappingId, item.View.Address), item with { View = localView }, subject, resolver, lease, generation, item, TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds)));
}
var snapshot = new ProjectedParentSnapshot(ProjectionPageStatus.Ready, Array.AsReadOnly(results.ToArray()), branch.Complete, null, generation, lease, binding.LocalAuthority, parentProof);
var prepared = new PreparedPage(_cache, _cursors, request, snapshot, continuationBinding, cursor, branch.Continuation, connection, _fetchSlots, Clock, branch.Lease.Duration < maxLease ? branch.Lease.Duration : maxLease, binding.Mapping.MaxProjectionNodes);
cursor = null; connection = null; transferred = true; return prepared;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception) { return PreparedPage.Failed(ProjectionPageStatus.Unavailable); }
finally
{
cursor?.Dispose();
if (!transferred)
{
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
finally { _fetchSlots.Release(); }
}
}
}
private bool IsCurrent(ProjectedMappingBinding binding)
{
lock (_sync) return !_disposed && _mappings.TryGetValue(binding.Mapping.RemoteNamespaceMappingId, out var current) && ReferenceEquals(current, binding);
}
public void Dispose()
{
ProjectedMappingBinding[] old;
lock (_sync)
{
if (_disposed) return; _disposed = true; old = _mappings.Values.ToArray(); _mappings.Clear();
foreach (var work in _fetches.Values) _ = work.Stop.CancelAsync();
}
foreach (var item in old) _cache.MarkUnavailable(item.Mapping.RemoteNamespaceMappingId, item.LocalAnchor);
_cache.Invalidated -= OnInvalidated;
}
}
@@ -28,6 +28,7 @@ using ZB.MOM.WW.OtOpcUa.Core.VirtualTags;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
using ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms;
using ZB.MOM.WW.OtOpcUa.Runtime.Telemetry;
@@ -663,6 +664,35 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// <param name="Reason">Failure detail when <paramref name="Success"/> is false; null on success.</param>
public sealed record NodeWriteResult(bool Success, string? Reason);
internal sealed record RouteRichWrite(WriteAdmissionTicket Ticket, WriteClaim Claim);
internal sealed record DrainProjectedValues(ActorProjectedValuePublisher Publisher);
internal sealed record DrainProjectedRetirements(ActorProjectedValuePublisher Publisher);
private readonly Dictionary<string, ProjectedValueRoute> _projectedRoutes = new(StringComparer.Ordinal);
private readonly ActorProjectedValuePublisher? _projectedPublisher;
private void ForwardProjected(DrainProjectedValues message)
{
foreach (var batch in message.Publisher.TakeQueuedValues(Self))
{
if (!batch.IsValid || _opcUaPublishActor is null) { batch.AbortQueued(); continue; }
foreach (var route in batch.Routes)
{
var key = route.DependencyReference;
if (_projectedRoutes.TryGetValue(key, out var old) && old != route)
_dependencyMux?.Tell(new DependencyMuxActor.ProjectedReferenceRetired(old.PublicationId.ToString("N"), old.DependencyReference));
_projectedRoutes[key] = route;
}
message.Publisher.EnqueueForSdk(batch, _opcUaPublishActor, _dependencyMux);
}
}
private void RetireProjected(DrainProjectedRetirements message)
{
foreach (var key in message.Publisher.TakeRetiredReferences(Self))
{
if (!_projectedRoutes.TryGetValue(key, out var current) || message.Publisher.IsCurrent(current)) continue;
_projectedRoutes.Remove(key);
_dependencyMux?.Tell(new DependencyMuxActor.ProjectedReferenceRetired(current.PublicationId.ToString("N"), current.DependencyReference));
}
}
/// <summary>
/// Routes an inbound native-condition acknowledge to the owning driver child. The host wires the
@@ -843,7 +873,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
DataWriteRuntime? dataWriteRuntime = null,
SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
DataConnectionDeploymentRuntime? dataConnections = null) =>
DataConnectionDeploymentRuntime? dataConnections = null,
ActorProjectedValuePublisher? projectedPublisher = null) =>
// WARNING: this forwarding list is POSITIONAL, and Props.Create compiles it into an
// expression tree. Six IActorRef? parameters and several interface-typed ones mean a
// mis-ordered argument is usually type-compatible and therefore compiles clean, then binds
@@ -858,7 +889,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
sharesHistorizationScopeWithLocal, applyWedgeTimeout, reprovisionBackoff, commsRecoveryAuditDelay,
sharesAlarmQueueWithLocal, applyOutcomeTimeout, captureWhilePrimaryUnreachable, historyUpdateRoleView,
scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout,
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime, acquisitionCapacity, dataConnections));
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime, acquisitionCapacity, dataConnections, projectedPublisher));
/// <summary>Initializes a new DriverHostActor with the specified dependencies.</summary>
/// <param name="dbFactory">Database context factory for configuration database access.</param>
@@ -999,8 +1030,10 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
DataWriteRuntime? dataWriteRuntime = null,
SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
DataConnectionDeploymentRuntime? dataConnections = null)
DataConnectionDeploymentRuntime? dataConnections = null,
ActorProjectedValuePublisher? projectedPublisher = null)
{
_projectedPublisher = projectedPublisher;
_dataWriteRuntime = dataWriteRuntime;
_dataConnections = dataConnections;
_acquisitionCapacity = acquisitionCapacity;
@@ -1059,6 +1092,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// <inheritdoc />
protected override void PreStart()
{
_projectedPublisher?.HostActivated(Self);
// Resolve the cluster DPS mediator once, on the actor thread, and reuse it for every subscribe +
// the Primary-gated native-alarm alerts fan-out in ForwardNativeAlarm (mirrors ScriptedAlarmHostActor).
_mediator = DistributedPubSub.Get(Context.System).Mediator;
@@ -1728,6 +1762,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
Receive<ApplyWedged>(HandleApplyWedged);
Receive<GetDiagnostics>(HandleGetDiagnostics);
Receive<DriverInstanceActor.AttributeValueBatchPublished>(ForwardBatchToMux);
Receive<DrainProjectedValues>(ForwardProjected);
Receive<DrainProjectedRetirements>(RetireProjected);
Receive<Terminated>(OnRetiredChildTerminated);
Receive<ScriptedAlarmHostActor.ScriptedAlarmHostRestarted>(_ => HandleScriptedAlarmHostRestarted());
Receive<DriverInstanceActor.AttributeAlarmPublished>(ForwardNativeAlarm);
@@ -1806,6 +1842,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
Receive<ApplyWedged>(HandleApplyWedged);
Receive<GetDiagnostics>(HandleGetDiagnostics);
Receive<DriverInstanceActor.AttributeValueBatchPublished>(ForwardBatchToMux);
Receive<DrainProjectedValues>(ForwardProjected);
Receive<DrainProjectedRetirements>(RetireProjected);
Receive<Terminated>(OnRetiredChildTerminated);
Receive<ScriptedAlarmHostActor.ScriptedAlarmHostRestarted>(_ => HandleScriptedAlarmHostRestarted());
Receive<DriverInstanceActor.AttributeAlarmPublished>(ForwardNativeAlarm);
@@ -2901,6 +2939,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
// spawned, so none should arrive — but the orphan-replay BeginDirectApply in that same try block has
// already started a pipe-back before the catch can run, so "cannot happen" rests on ordering. Explicit
// drops, so a burst that does land is a logged drop rather than an Unhandled dead-letter.
Receive<DrainProjectedValues>(m => { foreach (var batch in m.Publisher.TakeQueuedValues(Self)) batch.AbortQueued(); });
Receive<DrainProjectedRetirements>(RetireProjected);
Receive<DriverInstanceActor.AttributeValueBatchPublished>(m =>
_log.Debug("DriverHost {Node}: dropping a {Count}-item value burst from {Id} while Stale (no address space)",
_localNode, m.Items.Count, m.DriverInstanceId));
@@ -3637,7 +3677,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
_dataConnections.Apply(new(parsed.ParseDataConnectionScopeVersion(), _catalogAttempt.Revision,
parsed.ParseDataConnections(_localNode.Value), mode));
}
if (snapshot is not null) _catalogCoordinator.Stage(_catalogAttempt, snapshot, _localNode.Value);
if (snapshot is not null && _catalogCoordinator.Stage(_catalogAttempt, snapshot, _localNode.Value))
_catalogCoordinator.ProjectedMappings?.Stage(_catalogAttempt,
parsed.ParseRemoteNamespaceMappings(_localNode.Value), parsed.ParseDataConnections(_localNode.Value));
}
catch (Exception ex)
{
@@ -365,6 +365,7 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
ReceiveAsync<VirtualTagActor.DependencyValueChanged>(OnValueChangedAsync);
ReceiveAsync<VirtualTagActor.DependencyValueBatch>(OnValueBatchAsync);
ReceiveAsync<DependencyMuxActor.ProjectedDependencyWake>(wake => wake.ConsumeAsync(IngestAsync));
Receive<UpdateHistorizedRefs>(OnUpdateHistorizedRefs);
Receive<DrainTick>(_ => OnDrainTick());
Receive<DrainResult>(OnDrainResult);
@@ -470,11 +471,19 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
// production recorder died (Gitea #491): the throw reached supervision, the restart discarded the EMPTY-seeded ref
// set, and historization stopped after the first value. The append loop holds its own captured Self.
List<HistorizationOutboxEntry>? entries = null;
List<ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof?>? admissionProofs = null;
for (int i = 0; i < items.Count; i++)
{
try
{
var before = entries?.Count ?? 0;
CollectEntries(items[i], ref entries);
var added = (entries?.Count ?? 0) - before;
if (added > 0)
{
admissionProofs ??= Enumerable.Repeat<ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof?>(null, before).ToList();
for (var n = 0; n < added; n++) admissionProofs.Add(items[i].PublicationProof);
}
}
catch (Exception ex)
{
@@ -524,18 +533,45 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
// The gauges' source: the queue depth and the mailbox depth as this burst is accepted (the actor thread is the
// only place the mailbox can be read).
ContinuousHistorizationMetrics.ReportRecorder(pending, Context is ActorCell cell ? cell.NumberOfMessages : -1);
if (!_appendQueue.Writer.TryWrite(entries))
if (admissionProofs is not null && admissionProofs.Any(x => x is not null))
{
Interlocked.Increment(ref _appendBackpressureWaits);
// For projected input, the last proof check immediately before a successful bounded
// queue write is the accepted-history boundary. A full queue never extends authority.
try
{
await _appendQueue.Writer.WriteAsync(entries, _lifetime.Token).ConfigureAwait(false);
while (true)
{
var admitted = new List<HistorizationOutboxEntry>(entries.Count);
for (var i = 0; i < entries.Count; i++)
{
var proof = admissionProofs[i];
var valid = proof is null;
if (proof is not null) try { valid = proof.IsValid; } catch (Exception) { valid = false; }
if (valid) admitted.Add(entries[i]);
}
if (admitted.Count == 0)
{
ContinuousHistorizationMetrics.ReportPendingAppends(Interlocked.Decrement(ref _pendingAppends));
break;
}
if (_appendQueue.Writer.TryWrite(admitted)) break;
Interlocked.Increment(ref _appendBackpressureWaits);
if (!await _appendQueue.Writer.WaitToWriteAsync(_lifetime.Token).ConfigureAwait(false))
{
ContinuousHistorizationMetrics.ReportPendingAppends(Interlocked.Decrement(ref _pendingAppends));
break;
}
}
}
catch (Exception ex) when (ex is OperationCanceledException or ChannelClosedException)
{
// Normal shutdown raced the enqueue — not a fault.
ContinuousHistorizationMetrics.ReportPendingAppends(Interlocked.Decrement(ref _pendingAppends));
}
{ ContinuousHistorizationMetrics.ReportPendingAppends(Interlocked.Decrement(ref _pendingAppends)); }
}
else if (!_appendQueue.Writer.TryWrite(entries))
{
Interlocked.Increment(ref _appendBackpressureWaits);
try { await _appendQueue.Writer.WriteAsync(entries, _lifetime.Token).ConfigureAwait(false); }
catch (Exception ex) when (ex is OperationCanceledException or ChannelClosedException)
{ ContinuousHistorizationMetrics.ReportPendingAppends(Interlocked.Decrement(ref _pendingAppends)); }
}
}
@@ -625,6 +661,7 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
// mux ref under a HistorianTagname override, and there can be MORE THAN ONE when several historized
// equipment tags alias the same driver ref. (The mux already scopes to our registered refs; this is
// also the defensive filter.)
if (msg.PublicationProof is { IsValid: false }) return;
if (!_refMap.TryGetValue(msg.TagId, out HashSet<string>? historianNames) || historianNames.Count == 0)
{
return;
@@ -556,6 +556,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
Receive<AttributeValueUpdate>(HandleAttributeUpdate);
Receive<AttributeValueBatchUpdate>(HandleAttributeBatchUpdate);
Receive<ProjectedValues>(HandleProjectedValues);
Receive<DrainProjectedValues>(message =>
{ foreach (var batch in message.Publisher.TakeSdkValues(Self)) HandleProjectedValues(new(batch, message.DependencyMux)); });
Receive<AttributeStatusBatchUpdate>(HandleAttributeStatusBatchUpdate);
Receive<AlarmStateUpdate>(HandleAlarmUpdate);
Receive<AlarmQualityUpdate>(HandleAlarmQualityUpdate);
@@ -658,6 +661,24 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
}
}
internal sealed record ProjectedValues(DataConnections.ProjectedPublicationBatch Batch, IActorRef? DependencyMux);
internal sealed record DrainProjectedValues(DataConnections.ActorProjectedValuePublisher Publisher, IActorRef? DependencyMux);
private void HandleProjectedValues(ProjectedValues message)
{
var batch = message.Batch;
if (!batch.TryBegin()) return;
var accepted = false;
try
{
if (!batch.IsValid || _sink is not Core.Abstractions.DataConnections.IProjectedValueSink projected
|| !projected.TryPublish(batch.Writes) || !batch.IsValid) return;
if (message.DependencyMux is not null && !batch.ForwardToMux(message.DependencyMux)) return;
accepted = true;
}
finally { batch.Complete(accepted); }
}
private void HandleAttributeUpdate(AttributeValueUpdate msg)
{
try
@@ -801,7 +822,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
{
if (!string.Equals(_catalogCoordinator.Serving.NodeId, _localNode.Value.Value, StringComparison.Ordinal)) return;
var snapshot = parsed.ParseLocalCatalogSnapshot(_localNode.Value.Value);
if (snapshot is not null) _catalogCoordinator.Stage(msg.CatalogAttempt, snapshot, _localNode.Value.Value);
if (snapshot is not null && _catalogCoordinator.Stage(msg.CatalogAttempt, snapshot, _localNode.Value.Value))
_catalogCoordinator.ProjectedMappings?.Stage(msg.CatalogAttempt,
parsed.ParseRemoteNamespaceMappings(_localNode.Value.Value), parsed.ParseDataConnections(_localNode.Value.Value));
}
catch (Exception ex)
{
@@ -25,7 +25,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms;
/// snapshot — a concurrent unsubscribe can never corrupt an in-flight fan-out.
/// </para>
/// </remarks>
public sealed class DependencyMuxTagUpstreamSource : ITagUpstreamSource
public sealed class DependencyMuxTagUpstreamSource : ITagUpstreamSource, IAlarmInputEvidenceSource
{
// The status an "unknown path" snapshot carries — a path nothing has ever pushed to.
//
@@ -46,6 +46,51 @@ public sealed class DependencyMuxTagUpstreamSource : ITagUpstreamSource
// ONLY through RetainOnly — the host calls it with the loaded dependency-ref union after every
// (re)load, so a renamed/removed raw path (a RawTree rename is a surgical remove+add) stops
// costing a boxed value + two DateTimes for the process lifetime (R02:L3).
private readonly System.Runtime.CompilerServices.ConditionalWeakTable<DataValueSnapshot, IAlarmInputEvidence> _evidence = new();
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedByteQuota _physicalQuota;
private sealed class ProjectedEvidence(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof proof,
DataValueSnapshot snapshot, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedByteQuota quota) : IAlarmInputPhysicalEvidence
{
private readonly WeakReference<DataValueSnapshot> _identity = new(snapshot);
public bool IsValid { get { try { return proof.IsValid; } catch (Exception) { return false; } } }
public bool TryRetainPhysical(DataValueSnapshot exactSnapshot, out IDisposable? lease)
{
lease = null;
if (!_identity.TryGetTarget(out var original) || !ReferenceEquals(original, exactSnapshot) || !IsValid) return false;
long charge;
try { charge = checked(512L + ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.OwnedDataSample.Estimate(exactSnapshot.Value)); }
catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; }
if (!quota.TryAdjust(charge)) return false;
if (!ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ProjectedInputBudget.TryRetain([exactSnapshot], out var processLease) || processLease is null)
{ quota.TryAdjust(-charge); return false; }
if (!IsValid) { processLease.Dispose(); quota.TryAdjust(-charge); return false; }
lease = new PhysicalLease(quota, charge, exactSnapshot, processLease); return true;
}
private sealed class PhysicalLease(ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedByteQuota quota, long charge,
DataValueSnapshot snapshot, IDisposable processLease) : IDisposable
{
private DataValueSnapshot? _snapshot = snapshot;
public void Dispose()
{
if (Interlocked.Exchange(ref _snapshot, null) is null) return;
processLease.Dispose();
quota.TryAdjust(-charge);
}
}
}
public IAlarmInputEvidence? CaptureEvidence(DataValueSnapshot exactSnapshot)
{
ArgumentNullException.ThrowIfNull(exactSnapshot);
return _evidence.TryGetValue(exactSnapshot, out var evidence) ? evidence : null;
}
/// <summary>Copies a projected input and binds evidence to that exact immutable snapshot.</summary>
public void Push(string path, DataValueSnapshot snapshot, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof proof)
{
ArgumentNullException.ThrowIfNull(snapshot); ArgumentNullException.ThrowIfNull(proof);
var owned = snapshot with { };
_evidence.Add(owned, new ProjectedEvidence(proof, owned, _physicalQuota));
Push(path, owned);
}
private readonly ConcurrentDictionary<string, DataValueSnapshot> _cache
= new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, ImmutableList<Action<string, DataValueSnapshot>>> _observers
@@ -60,8 +105,12 @@ public sealed class DependencyMuxTagUpstreamSource : ITagUpstreamSource
/// snapshot returned for an unknown path. Defaults to <see cref="DateTime.UtcNow"/>,
/// mirroring how <see cref="ScriptedAlarmEngine"/> takes its clock.
/// </param>
public DependencyMuxTagUpstreamSource(Func<DateTime>? clock = null)
=> _clock = clock ?? (() => DateTime.UtcNow);
public DependencyMuxTagUpstreamSource(Func<DateTime>? clock = null, long maximumProjectedBytes = 16 * 1024 * 1024)
{
if (maximumProjectedBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maximumProjectedBytes));
_clock = clock ?? (() => DateTime.UtcNow);
_physicalQuota = new(maximumProjectedBytes);
}
/// <summary>
/// Update the cached snapshot for <paramref name="path"/> and then notify every
@@ -314,6 +314,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
// burst. The engine upstream is fed per value, so push each item in order — the saving is the
// mailbox hop, not the push.
Receive<VirtualTagActor.DependencyValueBatch>(OnDependencyBatch);
Receive<DependencyMuxActor.ProjectedDependencyWake>(wake => wake.Consume(items => OnDependencyBatch(new(items))));
Receive<EngineEmission>(OnEngineEmission);
// Cluster redundancy snapshots (published on the `redundancy-state` topic, subscribed in PreStart)
// cache this node's role so OnEngineEmission can gate the cluster-wide alerts publish to the Primary.
@@ -512,8 +513,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
// the status code rides through verbatim. This used to convert the incoming value onto a
// 3-state enum and straight back again through a pair of mutually-inverse mappers, which is where
// the input's sub-code was lost before the engine ever cached it.
_upstream.Push(msg.TagId,
new DataValueSnapshot(msg.Value, msg.StatusCode, msg.TimestampUtc, msg.TimestampUtc));
var snapshot = new DataValueSnapshot(msg.Value, msg.StatusCode, msg.TimestampUtc, msg.TimestampUtc);
if (msg.PublicationProof is { } proof) _upstream.Push(msg.TagId, snapshot, proof);
else _upstream.Push(msg.TagId, snapshot);
}
/// <summary>One batched mux delivery — every item already matched this host's registered interest.
@@ -544,6 +546,11 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
private void OnEngineEmission(EngineEmission msg)
{
var e = msg.Event;
if (e.InputEvidence is { } evidence)
{
try { if (!evidence.IsValid) return; }
catch (Exception) { return; }
}
// None = no meaningful change; Suppressed = shelving ate the emission. Neither should reach a
// sink. (The engine already filters these out of BuildEmission, but guard defensively.)
@@ -448,7 +448,8 @@ public static class ServiceCollectionExtensions
// Dependency mux must be spawned before DriverHostActor so the host can forward
// AttributeValueBatchPublished into it from the very first driver spawn.
var mux = system.ActorOf(DependencyMuxActor.Props(), DependencyMuxActorName);
var mux = system.ActorOf(DependencyMuxActor.Props(interestSink:
resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.IProjectedDependencyInterestSink>()), DependencyMuxActorName);
registry.Register<DependencyMuxActorKey>(mux);
// Per-cluster mesh Phase 2: the node end of the central↔node command boundary. Spawned
@@ -566,6 +567,8 @@ public static class ServiceCollectionExtensions
// consumers then behave as if the endpoint were listening (the pre-#762 behaviour).
var endpointState = resolver.GetService<IOpcUaEndpointState>();
var redundancy = resolver.GetService<WarmRedundancySettings>() ?? WarmRedundancySettings.Unset;
// Attach mapped deployment ownership before either actor can begin catalog activation.
_ = resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedMappingDeploymentRuntime>();
// The same production factory selects authority, catalog and Warm publications in tests.
var publishActor = system.ActorOf(
DataConnectionPublisherProps.Create(resolver, addressSpaceSink, serviceLevel,
@@ -671,7 +674,8 @@ public static class ServiceCollectionExtensions
dataWriteRuntime: resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.DataWriteRuntime>(),
acquisitionCapacity: resolver.GetService<SubscriptionAcquisitionCapacity>(),
writeClock: resolver.GetService<TimeProvider>(),
dataConnections: resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.DataConnectionDeploymentRuntime>()),
dataConnections: resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.DataConnectionDeploymentRuntime>(),
projectedPublisher: resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ActorProjectedValuePublisher>()),
DriverHostActorName);
registry.Register<DriverHostActorKey>(driverHost);
@@ -1,6 +1,7 @@
using Akka.Actor;
using Akka.Event;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
@@ -17,8 +18,8 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
/// <para>
/// This is the exact seam a <c>VirtualTagActor</c> uses to receive its inputs, generalised so a
/// host-blind driver (the <c>Calculation</c> pseudo-driver) can read other tags' live values with
/// no cross-driver plumbing. The mux fans out value + timestamp only (quality is stripped at the
/// mux boundary, same as for virtual tags), so the forwarded status code is <c>Good</c> (0).
/// no cross-driver plumbing. The mux preserves value, original timestamp and status; projected
/// samples additionally carry live publication proof checked immediately before the callback.
/// </para>
/// </summary>
public sealed class DependencyConsumerMuxAdapter : ReceiveActor
@@ -48,6 +49,7 @@ public sealed class DependencyConsumerMuxAdapter : ReceiveActor
Receive<VirtualTagActor.DependencyValueChanged>(OnDependencyValueChanged);
Receive<VirtualTagActor.DependencyValueBatch>(OnDependencyValueBatch);
Receive<DependencyMuxActor.ProjectedDependencyWake>(wake => wake.Consume(items => OnDependencyValueBatch(new(items))));
Receive<ReRegister>(_ => RegisterInterest());
}
@@ -84,6 +86,17 @@ public sealed class DependencyConsumerMuxAdapter : ReceiveActor
/// <param name="msg">The dependency value, as the mux delivered it.</param>
private void OnDependencyValueChanged(VirtualTagActor.DependencyValueChanged msg)
{
if (msg.PublicationProof is { } proof)
{
var valid = false;
try { valid = proof.IsValid; } catch (Exception) { }
if (_consumer is IProjectedDependencyConsumer projected)
projected.OnProjectedDependencyValue(msg.TagId, valid ? msg.Value : null,
valid ? msg.StatusCode : OpcUaStatus.BadNoCommunication, msg.TimestampUtc, proof);
else
_consumer.OnDependencyValue(msg.TagId, null, OpcUaStatus.BadNoCommunication, msg.TimestampUtc);
return;
}
_consumer.OnDependencyValue(msg.TagId, msg.Value, msg.StatusCode, msg.TimestampUtc);
}
@@ -1,6 +1,7 @@
using Akka.Actor;
using Akka.Event;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
@@ -91,6 +92,20 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
/// never replayed. Subscriptions are untouched.</summary>
/// <param name="DriverInstanceId">The removed driver instance.</param>
public sealed record SourceRemoved(string DriverInstanceId);
internal sealed record ProjectedDependency(string SourceId, string Reference, ProjectedValueWrite Value);
internal sealed record ProjectedBatch(IReadOnlyList<ProjectedDependency> Items);
internal sealed record DrainProjectedBatch(ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedCoalescingMailbox<ProjectedDependency> Mailbox);
internal sealed record ProjectedReferenceRetired(string SourceId, string Reference);
/// <summary>Payload-free projected delivery wake. Consume synchronously on the recipient actor.</summary>
public sealed class ProjectedDependencyWake
{
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedCoalescingMailbox<VirtualTagActor.DependencyValueChanged> _mailbox;
internal ProjectedDependencyWake(ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedCoalescingMailbox<VirtualTagActor.DependencyValueChanged> mailbox) => _mailbox = mailbox;
public void Consume(Action<IReadOnlyList<VirtualTagActor.DependencyValueChanged>> accept)
{ ArgumentNullException.ThrowIfNull(accept); using var batch = _mailbox.Take(); accept(batch.Items); }
public async Task ConsumeAsync(Func<IReadOnlyList<VirtualTagActor.DependencyValueChanged>, Task> accept)
{ ArgumentNullException.ThrowIfNull(accept); using var batch = _mailbox.Take(); await accept(batch.Items).ConfigureAwait(false); }
}
/// <summary>One VirtualTag result, routed to the tags that read it (lmxopcua#791). Always retained (see the
/// type remarks), so a dependent registering later is replayed the current value.</summary>
@@ -129,6 +144,7 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
public VirtualTagActor.DependencyValueChanged? Last;
public string? LastSource;
public long ProjectedCharge;
/// <summary>A VirtualTag output (lmxopcua#791): retained unconditionally until
/// <see cref="VirtualTagOutputsRemoved"/>, never put into grace.</summary>
@@ -147,8 +163,13 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
private sealed record Registration(HashSet<string> Refs, bool Replay);
private const long ProjectedBytesLimit = 16 * 1024 * 1024;
private const int ProjectedEntryLimit = 10000;
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedByteQuota _projectedQuota = new(ProjectedBytesLimit);
private readonly Dictionary<IActorRef, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedCoalescingMailbox<VirtualTagActor.DependencyValueChanged>> _projectedSubscribers = new();
private readonly Dictionary<string, RefEntry> _byRef = new(StringComparer.Ordinal);
private readonly Dictionary<IActorRef, Registration> _bySubscriber = new();
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.IProjectedDependencyInterestSink? _interestSink;
private readonly ILoggingAdapter _log = Context.GetLogger();
/// <summary>How long a released ref's value is kept.</summary>
@@ -167,34 +188,48 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
/// <param name="retentionGrace">How long a ref's value outlives its last replay-opting subscriber;
/// null ⇒ <see cref="DefaultRetentionGrace"/>.</param>
/// <returns>The props for creating this actor.</returns>
public static Props Props(TimeSpan? retentionGrace = null)
public static Props Props(TimeSpan? retentionGrace = null, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.IProjectedDependencyInterestSink? interestSink = null)
{
var grace = retentionGrace ?? DefaultRetentionGrace;
return Akka.Actor.Props.Create(() => new DependencyMuxActor(grace));
return Akka.Actor.Props.Create(() => new DependencyMuxActor(grace, interestSink));
}
/// <summary>Initializes a new instance of the <see cref="DependencyMuxActor"/> class.</summary>
/// <param name="retentionGrace">See <see cref="Props"/>; non-positive ⇒ <see cref="DefaultRetentionGrace"/>.</param>
public DependencyMuxActor(TimeSpan retentionGrace)
public DependencyMuxActor(TimeSpan retentionGrace, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.IProjectedDependencyInterestSink? interestSink = null)
{
RetentionGrace = retentionGrace > TimeSpan.Zero ? retentionGrace : DefaultRetentionGrace;
_interestSink = interestSink;
Receive<RegisterInterest>(OnRegister);
Receive<UnregisterInterest>(msg => RemoveSubscriber(msg.Subscriber));
Receive<SourceRemoved>(OnSourceRemoved);
Receive<SweepReleased>(_ => OnSweep());
Receive<DriverInstanceActor.AttributeValueBatchPublished>(OnAttributeValueBatchPublished);
Receive<ProjectedBatch>(OnProjectedBatch);
Receive<DrainProjectedBatch>(message => { using var batch = message.Mailbox.Take(); OnProjectedBatch(new(batch.Items)); });
Receive<ProjectedReferenceRetired>(OnProjectedReferenceRetired);
Receive<VirtualTagOutput>(OnVirtualTagOutput);
Receive<VirtualTagOutputsRemoved>(OnVirtualTagOutputsRemoved);
Receive<Terminated>(msg => RemoveSubscriber(msg.ActorRef));
Receive<Terminated>(msg => { RemoveSubscriber(msg.ActorRef); if (_projectedSubscribers.Remove(msg.ActorRef, out var mailbox)) mailbox.Dispose(); });
}
protected override void PostStop()
{
foreach (var pair in _byRef) if (pair.Value.Subscribers.Count > 0) NotifyInterest(pair.Key, false);
foreach (var mailbox in _projectedSubscribers.Values) mailbox.Dispose();
_projectedSubscribers.Clear();
base.PostStop();
}
private void OnRegister(RegisterInterest msg)
{
// Replace any prior interest set so re-registers on actor restart don't leak old refs. Detaching first
// may put a ref into grace; the re-attach below takes it straight back out.
Detach(msg.Subscriber);
var refs = new HashSet<string>(msg.TagRefs, StringComparer.Ordinal);
var preserved = _bySubscriber.TryGetValue(msg.Subscriber, out var prior)
? new HashSet<string>(prior.Refs.Where(refs.Contains), StringComparer.Ordinal) : new HashSet<string>(StringComparer.Ordinal);
Detach(msg.Subscriber, preserved);
_bySubscriber[msg.Subscriber] = new Registration(refs, msg.ReplayRetained);
List<VirtualTagActor.DependencyValueChanged>? replay = null;
foreach (var r in refs)
@@ -204,12 +239,17 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
entry = new RefEntry();
_byRef[r] = entry;
}
if (entry.Subscribers.Count == 0 && !preserved.Contains(r)) NotifyInterest(r, true);
entry.Subscribers.Add(msg.Subscriber);
if (!msg.ReplayRetained) continue;
entry.Replayers++;
entry.ReleasedAtUtc = null;
if (entry.Last is { } retained)
(replay ??= []).Add(retained);
{
if (retained.PublicationProof is null) (replay ??= []).Add(retained);
else if (retained.PublicationProof.IsValid) OfferProjected(msg.Subscriber, [retained]);
else Forget(entry);
}
}
Context.Watch(msg.Subscriber);
_log.Debug("DependencyMux: subscriber {Sub} registered for {Count} refs (replay {Replay})",
@@ -224,16 +264,24 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
}
}
private void NotifyInterest(string reference, bool active)
{
if (_interestSink is null || !ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ProjectedDataIds.TryParseDependencyReference(reference, out _, out _)) return;
try { _interestSink.SetInterest(reference, active); }
catch (Exception ex) { _log.Error(ex, "Projected dependency interest transition failed"); }
}
private void RemoveSubscriber(IActorRef subscriber)
{
if (!Detach(subscriber)) return;
if (_projectedSubscribers.TryGetValue(subscriber, out var projectedMailbox)) projectedMailbox.Clear();
Context.Unwatch(subscriber);
_log.Debug("DependencyMux: subscriber {Sub} removed", subscriber);
}
/// <summary>Drop <paramref name="subscriber"/>'s registration. A ref losing its last replay-opting
/// subscriber goes into grace; a ref left with no state at all is removed.</summary>
private bool Detach(IActorRef subscriber)
private bool Detach(IActorRef subscriber, HashSet<string>? preserved = null)
{
if (!_bySubscriber.Remove(subscriber, out var registration)) return false;
var now = DateTime.UtcNow;
@@ -242,6 +290,7 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
{
if (!_byRef.TryGetValue(r, out var entry)) continue;
entry.Subscribers.Remove(subscriber);
if (entry.Subscribers.Count == 0 && !(preserved?.Contains(r) ?? false)) NotifyInterest(r, false);
if (registration.Replay && --entry.Replayers == 0 && entry.Last is not null && !entry.Pinned)
{
entry.ReleasedAtUtc = now;
@@ -269,7 +318,7 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
stillInGrace = true;
continue;
}
entry.Forget();
Forget(entry);
if (entry.IsDead) (dead ??= []).Add(r);
}
if (dead is not null)
@@ -285,7 +334,7 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
{
if (entry.Last is null || !string.Equals(entry.LastSource, msg.DriverInstanceId, StringComparison.Ordinal))
continue;
entry.Forget();
Forget(entry);
evicted++;
if (entry.IsDead) (dead ??= []).Add(r);
}
@@ -304,6 +353,7 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
var dep = new VirtualTagActor.DependencyValueChanged(msg.TagRef, msg.Value, msg.TimestampUtc, msg.StatusCode);
entry.Pinned = true;
entry.ReleasedAtUtc = null;
ReleaseProjected(entry);
entry.Last = dep;
entry.LastSource = VirtualTagSource;
foreach (var sub in entry.Subscribers)
@@ -316,11 +366,78 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
{
if (!_byRef.TryGetValue(r, out var entry) || !entry.Pinned) continue;
entry.Pinned = false;
entry.Forget();
Forget(entry);
if (entry.IsDead) _byRef.Remove(r);
}
}
private void ReleaseProjected(RefEntry entry)
{
if (entry.ProjectedCharge == 0) return;
_projectedQuota.TryAdjust(-entry.ProjectedCharge); entry.ProjectedCharge = 0;
}
private void Forget(RefEntry entry) { ReleaseProjected(entry); entry.Forget(); }
private bool TryRetainProjected(RefEntry entry, VirtualTagActor.DependencyValueChanged value, string source)
{
long charge;
try { charge = checked(512L + 2L * value.TagId.Length + ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.OwnedDataSample.Estimate(value.Value)); }
catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; }
if (!_projectedQuota.TryAdjust(charge - entry.ProjectedCharge)) return false;
entry.ProjectedCharge = charge; entry.Last = value; entry.LastSource = source; return true;
}
private bool OfferProjected(IActorRef subscriber, IReadOnlyList<VirtualTagActor.DependencyValueChanged> values)
{
if (!_projectedSubscribers.TryGetValue(subscriber, out var mailbox))
{
if (_projectedSubscribers.Count >= ProjectedEntryLimit) return false;
mailbox = new(subscriber, queue => new ProjectedDependencyWake(queue), ProjectedBytesLimit, ProjectedEntryLimit, _projectedQuota, retainDelivered: true);
_projectedSubscribers.Add(subscriber, mailbox);
}
try
{
var entries = values.Select(value => (value.TagId, value,
checked(512L + 2L * value.TagId.Length + ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.OwnedDataSample.Estimate(value.Value)))).ToArray();
return mailbox.TryOffer(entries);
}
catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; }
}
private void OnProjectedReferenceRetired(ProjectedReferenceRetired message)
{
if (!_byRef.TryGetValue(message.Reference, out var entry) || entry.Last is not { } previous
|| entry.LastSource != message.SourceId && previous.PublicationProof is not { IsValid: false }) return;
Forget(entry);
var bad = new VirtualTagActor.DependencyValueChanged(message.Reference, null, DateTime.MinValue,
ZB.MOM.WW.OtOpcUa.Commons.OpcUa.OpcUaStatus.BadNoCommunication, previous.PublicationProof);
foreach (var subscriber in entry.Subscribers) OfferProjected(subscriber, [bad]);
if (entry.IsDead) _byRef.Remove(message.Reference);
}
private void OnProjectedBatch(ProjectedBatch message)
{
var perSubscriber = new Dictionary<IActorRef, List<VirtualTagActor.DependencyValueChanged>>();
foreach (var item in message.Items)
{
var value = item.Value;
if (!value.Proof.IsValid || !_byRef.TryGetValue(item.Reference, out var entry)) continue;
var dependency = new VirtualTagActor.DependencyValueChanged(item.Reference, value.Snapshot.Value,
value.Snapshot.SourceTimestampUtc ?? value.Snapshot.ServerTimestampUtc ?? DateTime.MinValue,
value.Snapshot.StatusCode, value.Proof);
if (entry.Retains && !TryRetainProjected(entry, dependency, item.SourceId)) { value.Proof.Invalidate(); continue; }
foreach (var subscriber in entry.Subscribers)
{
if (!perSubscriber.TryGetValue(subscriber, out var list)) perSubscriber[subscriber] = list = [];
list.Add(dependency);
}
}
foreach (var pair in perSubscriber)
{
var current = pair.Value.Where(item => item.PublicationProof!.IsValid).ToArray();
if (current.Length != 0 && !OfferProjected(pair.Key, current))
foreach (var item in current) item.PublicationProof?.Invalidate();
}
}
private void OnAttributeValueBatchPublished(DriverInstanceActor.AttributeValueBatchPublished msg)
{
// Nothing registered and nothing retained — skip the whole burst rather than probing an empty map per item.
@@ -340,6 +457,7 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
var dep = new VirtualTagActor.DependencyValueChanged(item.FullReference, item.Value, item.TimestampUtc, item.StatusCode);
if (entry.Retains)
{
ReleaseProjected(entry);
entry.Last = dep;
entry.LastSource = msg.DriverInstanceId;
}
@@ -79,7 +79,8 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
/// now holds evaluation while any declared input is Bad and inherits the worst input's status
/// otherwise. The Calculation driver reads it through the same mux.</para></summary>
public sealed record DependencyValueChanged(
string TagId, object? Value, DateTime TimestampUtc, uint StatusCode = OpcUaStatus.Good);
string TagId, object? Value, DateTime TimestampUtc, uint StatusCode = OpcUaStatus.Good,
Core.Abstractions.DataConnections.IProjectedSamplePublicationProof? PublicationProof = null);
/// <summary>
/// One subscriber's slice of one upstream burst: every item in this batch matched
@@ -132,6 +133,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
// comms-lost input from a genuine Good null, and it is what the script reads through
// ctx.GetTag(path).StatusCode.
private readonly Dictionary<string, DataValueSnapshot> _dependencies = new(StringComparer.Ordinal);
private readonly Dictionary<string, Core.Abstractions.DataConnections.IProjectedSamplePublicationProof> _projectedDependencyProofs = new(StringComparer.Ordinal);
private bool _hasLastValue;
private object? _lastValue;
@@ -231,6 +233,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
Receive<DependencyValueChanged>(OnDependencyChanged);
Receive<DependencyValueBatch>(OnDependencyBatch);
Receive<DependencyMuxActor.ProjectedDependencyWake>(wake => wake.Consume(items => OnDependencyBatch(new(items))));
Receive<ReassertValue>(_ => OnReassertValue());
Receive<RetrySourceBinding>(_ => RetrySource());
Receive<TimerTick>(_ => Evaluate(DateTime.UtcNow));
@@ -315,6 +318,8 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
private void OnReassertValue()
{
if (!_hasLastValue && !_hasPublished) return;
if (!ProjectedProofsValid())
{ OnInputsBad(OpcUaStatus.BadNoCommunication, DateTime.UtcNow); return; }
// The status LAST PUBLISHED, not a guess (02/S14). A VT whose input is comms-lost re-asserts
// BadNoCommunication onto the freshly-materialised node; re-asserting Good here would put the
// stale-Good lie back at every deploy.
@@ -324,6 +329,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
private void OnDependencyChanged(DependencyValueChanged msg)
{
SetDependencyProof(msg);
_dependencies[msg.TagId] = new DataValueSnapshot(msg.Value, msg.StatusCode, msg.TimestampUtc, msg.TimestampUtc);
if (_changeTriggered) Evaluate(msg.TimestampUtc);
}
@@ -348,6 +354,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
for (var i = 0; i < count; i++)
{
var item = items[i];
SetDependencyProof(item);
_dependencies[item.TagId] =
new DataValueSnapshot(item.Value, item.StatusCode, item.TimestampUtc, item.TimestampUtc);
}
@@ -361,6 +368,8 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
/// <param name="timestampUtc">The triggering dependency change's timestamp, stamped on the result.</param>
private void Evaluate(DateTime timestampUtc)
{
if (!ProjectedProofsValid())
{ OnInputsBad(OpcUaStatus.BadNoCommunication, timestampUtc); return; }
// Worst-of-input FIRST (02/S14), before the evaluator is even considered.
//
// Over the deps that have ARRIVED, deliberately — a never-pushed dep is cold start, not a fault,
@@ -380,7 +389,21 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
Task<VirtualTagEvalResult> evaluation;
try
{
evaluation = _evaluator.EvaluateAsync(_virtualTagId, _expression, _dependencies);
if (_projectedDependencyProofs.Count == 0)
evaluation = _evaluator.EvaluateAsync(_virtualTagId, _expression, _dependencies);
else
{
if (_evaluator is not IProjectedVirtualTagEvaluator projected ||
!Core.Abstractions.DataConnections.ProjectedInputBudget.TryRetain(
_projectedDependencyProofs.Keys.Select(key => _dependencies[key]), out var lease) || lease is null)
{
OnInputsBad(OpcUaStatus.BadNoCommunication, timestampUtc);
return;
}
var captured = new Dictionary<string, DataValueSnapshot>(_dependencies, StringComparer.Ordinal);
try { evaluation = projected.EvaluateProjectedAsync(_virtualTagId, _expression, captured, lease); }
catch { lease.Dispose(); throw; }
}
}
catch (Exception ex)
{
@@ -464,8 +487,26 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
/// <param name="evaluation">The completed evaluation task.</param>
/// <param name="worst">The worst input status at the trigger.</param>
/// <param name="timestampUtc">The trigger's timestamp.</param>
private bool ProjectedProofsValid()
{
foreach (var proof in _projectedDependencyProofs.Values)
{
try { if (!proof.IsValid) return false; }
catch (Exception) { return false; }
}
return true;
}
private void SetDependencyProof(DependencyValueChanged item)
{
if (item.PublicationProof is { } proof) _projectedDependencyProofs[item.TagId] = proof;
else _projectedDependencyProofs.Remove(item.TagId);
}
private void ApplyEvaluation(Task<VirtualTagEvalResult> evaluation, uint worst, DateTime timestampUtc)
{
if (!ProjectedProofsValid())
{ OnInputsBad(OpcUaStatus.BadNoCommunication, timestampUtc); return; }
if (!evaluation.IsCompletedSuccessfully)
{
var ex = evaluation.Exception?.GetBaseException()
@@ -494,7 +535,9 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
// A completed evaluation is a fresh acquisition even when the legacy SDK value is unchanged.
// Publish before the SDK dedup so a quiet equal value can recover an invalidated cache.
if (!ProjectedProofsValid()) { OnInputsBad(OpcUaStatus.BadNoCommunication, timestampUtc); return; }
PublishSource(result.Value, worst, timestampUtc);
if (!ProjectedProofsValid()) { OnInputsBad(OpcUaStatus.BadNoCommunication, timestampUtc); return; }
// Dedup on (value, STATUS) — 02/S14 generalising 02/S13's recover-from-Bad bypass. Keying on
// value alone swallows every recovery whose value is unchanged, which is what a device coming
@@ -513,6 +556,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
_lastPublishedStatus = worst;
OtOpcUaTelemetry.VirtualTagEval.Add(1, new KeyValuePair<string, object?>("outcome", "ok"));
var evalResult = new EvaluationResult(_virtualTagId, result.Value, timestampUtc, CorrelationId.NewId(), worst, SourceHandled: _sourcePublisher is not null);
if (!ProjectedProofsValid()) { OnInputsBad(OpcUaStatus.BadNoCommunication, timestampUtc); return; }
Context.Parent.Tell(evalResult);
}
@@ -600,6 +644,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
{
if (_sourcePublisher is null || _sourceIncarnation is not { } incarnation ||
!_sourcePublisher.TryCaptureVirtual(_virtualTagId, incarnation, out var ticket)) return;
if (!ProjectedProofsValid()) return;
_sourcePublisher.TryPublish(ticket, new DataValueSnapshot(value, status, timestamp, timestamp));
}