Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs
T

886 lines
53 KiB
C#

using Microsoft.Extensions.Logging;
using Opc.Ua;
using Opc.Ua.Server;
using Opc.Ua.Identity;
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;
/// <summary>
/// <see cref="StandardServer"/> subclass that wires in the v2 <see cref="OtOpcUaNodeManager"/>.
/// Exposes the live node manager after start so callers (<see cref="OpcUaApplicationHost"/>,
/// the fused Host's DI binding) can wrap it in a <see cref="SdkAddressSpaceSink"/> and hand
/// it to <c>OpcUaPublishActor</c>.
/// </summary>
public sealed class OtOpcUaSdkServer : StandardServer
{
private readonly ILogger<OtOpcUaNodeManager>? _nodeManagerLogger;
private OtOpcUaNodeManager? _otOpcUaNodeManager;
/// <summary>Initializes a new instance of the <see cref="OtOpcUaSdkServer"/> class.</summary>
/// <param name="nodeManagerLogger">Logger handed to the created <see cref="OtOpcUaNodeManager"/>;
/// <c>null</c> leaves it on a no-op logger.</param>
/// <param name="telemetry">The SDK telemetry context (<see cref="ServerSdkTelemetry.Create"/>, #874); <c>null</c>
/// discards the SDK's own log output.</param>
public OtOpcUaSdkServer(ILogger<OtOpcUaNodeManager>? nodeManagerLogger = null, ITelemetryContext? telemetry = null)
: base(telemetry ?? DefaultTelemetry.Create(_ => { })) => _nodeManagerLogger = nodeManagerLogger;
internal void ConfigureIdentityAuthenticators(IEnumerable<IUserTokenAuthenticator> authenticators) =>
AddPreStartupTask(new IdentityStartupTask(authenticators.ToArray()));
private sealed class IdentityStartupTask(IReadOnlyList<IUserTokenAuthenticator> authenticators) : IServerPreStartupTask
{
public ValueTask OnServerStartingAsync(IServerContext server, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
if (server is not IServerInternal internalServer)
throw new InvalidOperationException("Application identity registry unavailable during server startup.");
foreach (var authenticator in authenticators) internalServer.IdentityRegistry.Register(authenticator);
return ValueTask.CompletedTask;
}
}
private readonly AsyncLocal<System.Net.IPAddress?> _activationPeer = new();
/// <summary>The transport-observed peer of the current activation request, when available.</summary>
internal System.Net.IPAddress? ActivationPeerAddress => _activationPeer.Value;
/// <inheritdoc />
public override async ValueTask<ActivateSessionResponse> ActivateSessionAsync(
SecureChannelContext secureChannelContext,
RequestHeader? requestHeader,
SignatureData? clientSignature,
ArrayOf<SignedSoftwareCertificate> clientSoftwareCertificates,
ArrayOf<string> localeIds,
ExtensionObject userIdentityToken,
SignatureData? userTokenSignature,
RequestLifetime requestLifetime)
{
return await WithActivationPeerAddressAsync(secureChannelContext.PeerAddress,
() => base.ActivateSessionAsync(secureChannelContext, requestHeader, clientSignature,
clientSoftwareCertificates, localeIds, userIdentityToken, userTokenSignature, requestLifetime))
.ConfigureAwait(false);
}
internal async ValueTask<ActivateSessionResponse> WithActivationPeerAddressAsync(
System.Net.IPAddress? peer, Func<ValueTask<ActivateSessionResponse>> activation)
{
// AuthenticationContext does not carry the request peer in 2.0.1. Keep the public
// transport evidence in this activation's async flow, including reactivation on a new channel.
var previous = _activationPeer.Value;
_activationPeer.Value = peer;
try
{
return await activation().ConfigureAwait(false);
}
finally
{
_activationPeer.Value = previous;
}
}
/// <summary>The custom node manager once <c>StartAsync</c> has called
/// <see cref="CreateMasterNodeManager"/>. Null until the SDK has bootstrapped.</summary>
public OtOpcUaNodeManager? NodeManager => _otOpcUaNodeManager;
/// <summary>
/// Wire the reverse-path sink for inbound Part 9 alarm method calls onto the created
/// <see cref="OtOpcUaNodeManager"/>. The host calls this after start with a non-blocking
/// <c>mediator.Tell</c> that publishes each <see cref="AlarmCommand"/> onto the
/// <c>alarm-commands</c> DistributedPubSub topic. No-op (returns <c>false</c>) when the node
/// manager has not been created yet, so the caller can detect a too-early call.
/// </summary>
/// <param name="router">The router invoked by the condition handlers once the <c>AlarmAck</c>
/// gate passes; may be <c>null</c> to clear it.</param>
/// <returns><c>true</c> when the router was set on a live node manager; <c>false</c> when no node
/// manager exists yet.</returns>
public bool SetAlarmCommandRouter(Action<AlarmCommand>? router)
{
if (_otOpcUaNodeManager is null) return false;
_otOpcUaNodeManager.AlarmCommandRouter = router;
return true;
}
/// <summary>
/// Wire the reverse-path router for inbound Part 9 Acknowledge of a NATIVE (driver-fed, e.g. Galaxy)
/// condition onto the created <see cref="OtOpcUaNodeManager"/>. The host calls this after start with a
/// non-blocking router that Tells a <c>DriverHostActor.RouteNativeAlarmAck</c> into the local
/// <c>DriverHostActor</c>, which (Primary-gated) routes the acknowledge to the owning driver child.
/// Native conditions are not owned by the scripted-alarm engine, so the node manager branches their
/// inbound Acknowledge to this seam instead of the scripted <see cref="SetAlarmCommandRouter"/> path.
/// Passing <c>null</c> clears it. No-op (returns <c>false</c>) when the node manager has not been
/// created yet, so the caller can detect a too-early call (mirrors <see cref="SetAlarmCommandRouter"/>).
/// </summary>
/// <param name="router">The router invoked by the native condition's Acknowledge handler once the
/// <c>AlarmAck</c> gate passes; may be <c>null</c> to clear it.</param>
/// <returns><c>true</c> when the router was set on a live node manager; <c>false</c> when no node
/// manager exists yet.</returns>
public bool SetNativeAlarmAckRouter(Action<NativeAlarmAck>? router)
{
if (_otOpcUaNodeManager is null) return false;
_otOpcUaNodeManager.NativeAlarmAckRouter = router;
return true;
}
/// <summary>
/// Wire the redundancy verdict that decides whether this node accepts an OPC UA Acknowledge
/// of a NATIVE condition (<see cref="OtOpcUaNodeManager.NativeAlarmAckPrimaryGate"/>); on any other node
/// the ack is refused with <c>BadInvalidState</c> instead of being applied locally and reverted by the
/// driver's next transition. Passing <c>null</c> clears it (allow). No-op (returns <c>false</c>) when the
/// node manager has not been created yet (mirrors <see cref="SetNativeAlarmAckRouter"/>).
/// </summary>
/// <param name="isPrimary">A cheap, non-blocking read of the data-plane Primary verdict; null to allow.</param>
/// <returns><c>true</c> when set on a live node manager; <c>false</c> when no node manager exists yet.</returns>
public bool SetNativeAlarmAckPrimaryGate(Func<bool>? isPrimary)
{
if (_otOpcUaNodeManager is null) return false;
_otOpcUaNodeManager.NativeAlarmAckPrimaryGate = isPrimary;
return true;
}
/// <summary>
/// Wire the synchronous native-ack pre-check (<see cref="OtOpcUaNodeManager.NativeAlarmAckPreflight"/>,
/// lmxopcua#760). Passing <c>null</c> clears it. No-op (returns <c>false</c>) when the node manager has not
/// been created yet (mirrors <see cref="SetNativeAlarmAckRouter"/>).
/// </summary>
/// <param name="preflight">A lock-free read returning the refusal reason, or null to proceed.</param>
/// <returns><c>true</c> when set on a live node manager; <c>false</c> when no node manager exists yet.</returns>
public bool SetNativeAlarmAckPreflight(Func<NativeAlarmAck, string?>? preflight)
{
if (_otOpcUaNodeManager is null) return false;
_otOpcUaNodeManager.NativeAlarmAckPreflight = preflight;
return true;
}
/// <summary>
/// Wire the redundancy verdict that decides whether this node serves an OPC UA HistoryUpdate
/// (<see cref="OtOpcUaNodeManager.HistoryUpdatePrimaryGate"/>); on any other node every authorized node of a
/// HistoryUpdate is refused <c>BadInvalidState</c>. Passing <c>null</c> clears it (allow). No-op (returns
/// <c>false</c>) when the node manager has not been created yet (mirrors <see cref="SetNativeAlarmAckPrimaryGate"/>).
/// </summary>
/// <param name="isPrimary">A cheap, non-blocking read of the data-plane Primary verdict; null to allow.</param>
/// <returns><c>true</c> when set on a live node manager; <c>false</c> when no node manager exists yet.</returns>
public bool SetHistoryUpdatePrimaryGate(Func<bool>? isPrimary)
{
if (_otOpcUaNodeManager is null) return false;
_otOpcUaNodeManager.HistoryUpdatePrimaryGate = isPrimary;
return true;
}
/// <summary>
/// Wire the reverse-path gateway for inbound operator writes to writable equipment-tag nodes onto the
/// created <see cref="OtOpcUaNodeManager"/>. The host calls this after start with an
/// <c>ActorNodeWriteGateway</c> whose <c>WriteAsync</c> kicks off a bounded <c>Ask</c> of the local
/// <c>DriverHostActor</c> (<c>RouteNodeWrite</c>); the node manager calls it fire-and-forget and uses
/// the resolved <c>NodeWriteOutcome</c> to self-correct the node on a failed device write (mirrors
/// <see cref="SetAlarmCommandRouter"/>). Passing <c>null</c> restores the
/// <c>NullOpcUaNodeWriteGateway</c> default (writes unavailable). No-op (returns <c>false</c>) when the
/// node manager has not been created yet, so the caller can detect a too-early call.
/// </summary>
/// <param name="gateway">The gateway invoked by the writable node's <c>OnWriteValue</c> handler once the
/// <c>WriteOperate</c> gate passes; may be <c>null</c> to restore the Null default.</param>
/// <returns><c>true</c> when the gateway was set on a live node manager; <c>false</c> when no node
/// manager exists yet.</returns>
public bool SetNodeWriteGateway(IOpcUaNodeWriteGateway? gateway)
{
if (_otOpcUaNodeManager is null) return false;
// The NodeWriteGateway setter null-coalesces to the Null default, so a null gateway is intentional
// (restores "writes unavailable"); forgive the nullable-in here.
_otOpcUaNodeManager.NodeWriteGateway = gateway!;
return true;
}
/// <summary>
/// Wire the server-side HistoryRead backend (the <see cref="IHistorianDataSource"/> the node
/// manager's HistoryRead overrides block-bridge to) onto the created
/// <see cref="OtOpcUaNodeManager"/>. The host calls this after start with the DI-resolved source —
/// the <c>NullHistorianDataSource</c> default (GoodNoData-empty reads) or the configured HistorianGateway
/// read client. Passing <c>null</c> restores the Null default (the property setter null-coalesces),
/// i.e. "no historian". No-op (returns <c>false</c>) when the node manager has not been created yet,
/// so the caller can detect a too-early call (mirrors <see cref="SetNodeWriteGateway"/>).
/// </summary>
/// <param name="source">The read backend invoked by the node manager's HistoryRead overrides; may be
/// <c>null</c> to restore the Null default (GoodNoData-empty reads).</param>
/// <returns><c>true</c> when the source was set on a live node manager; <c>false</c> when no node
/// manager exists yet.</returns>
public bool SetHistorianDataSource(IHistorianDataSource? source)
{
if (_otOpcUaNodeManager is null) return false;
// The HistorianDataSource setter null-coalesces to the Null default, so a null source is intentional
// (restores GoodNoData-empty reads); forgive the nullable-in here.
_otOpcUaNodeManager.HistorianDataSource = source!;
return true;
}
/// <summary>
/// Wire the optional HistoryUpdate backend (the <see cref="IHistorianDataUpdater"/> the node manager's
/// HistoryUpdate overrides block-bridge to) onto the created <see cref="OtOpcUaNodeManager"/>. Mirrors
/// <see cref="SetHistorianDataSource"/>; <c>null</c> means "this backend cannot modify history".
/// <para>
/// ⚠️ Call this BEFORE any node materialises: whether an updater is wired decides the
/// <c>HistoryWrite</c> AccessLevel bit at materialise time, and the SDK base admits a node to
/// HistoryUpdate only when that bit is set. Nodes materialised earlier are not retro-updated.
/// </para>
/// </summary>
/// <param name="updater">The update backend, or <c>null</c> for none.</param>
/// <returns><c>true</c> when set on a live node manager; <c>false</c> when no node manager exists yet.</returns>
public bool SetHistorianDataUpdater(IHistorianDataUpdater? updater)
{
if (_otOpcUaNodeManager is null) return false;
_otOpcUaNodeManager.HistorianDataUpdater = updater;
return true;
}
/// <summary>
/// Wire the node's data-plane authorization inputs onto the created
/// <see cref="OtOpcUaNodeManager"/> — the cluster it serves, the current auth generation, and the
/// ACL grants. The host calls this after start with the DI-resolved
/// <see cref="IDataPlaneAuthoritySource"/>, which the artifact-apply path refreshes on every
/// deploy. Passing <c>null</c> restores the empty source (authorizes nothing). No-op (returns
/// <c>false</c>) when the node manager has not been created yet, so the caller can detect a
/// too-early call (mirrors <see cref="SetHistorianDataSource"/>).
/// </summary>
/// <param name="source">The node's data-plane authorization inputs; may be <c>null</c> to restore the
/// empty default.</param>
/// <returns><c>true</c> when the source was set on a live node manager; <c>false</c> when no node
/// manager exists yet.</returns>
public bool SetDataPlaneAuthority(IDataPlaneAuthoritySource? source)
{
if (_otOpcUaNodeManager is null) return false;
// The DataPlaneAuthority setter null-coalesces to the empty source, so a null is intentional;
// forgive the nullable-in here.
_otOpcUaNodeManager.DataPlaneAuthority = source!;
return true;
}
/// <summary>
/// Wire the node-scoped ACL gate onto the created <see cref="OtOpcUaNodeManager"/>.
/// The host calls this after start; passing <c>null</c> detaches it, which returns the write and
/// alarm seams to their server-wide role checks and leaves HistoryRead ungated. No-op (returns
/// <c>false</c>) when the node manager has not been created yet, mirroring
/// <see cref="SetDataPlaneAuthority"/>.
/// </summary>
/// <param name="authorizer">The gate, or <c>null</c> to detach.</param>
/// <returns><c>true</c> when set on a live node manager; <c>false</c> when none exists yet.</returns>
public bool SetDataPlaneAuthorizer(DataPlaneAuthorizer? authorizer)
{
if (_otOpcUaNodeManager is null) return false;
_otOpcUaNodeManager.Authorizer = authorizer;
return true;
}
// Register the same 37 standard aggregate IDs exactly once, using the versioned application
// calculators. Calling base first would create the diagnostic nodes twice: SDK 2.0.1's
// RegisterFactoryAsync replaces the factory but unconditionally adds another address-space node.
// HistoryServerCapabilities is then trimmed to the currently served historian aggregate set.
/// <inheritdoc />
protected override async ValueTask<AggregateManager> CreateAggregateManagerAsync(
IServerInternal server, ApplicationConfiguration configuration, CancellationToken cancellationToken = default)
{
var manager = new AggregateManager(server);
try
{
// Pin the SDK manager's default AggregateConfiguration (what live AggregateFilter subscriptions compute under
// and what the server advertises) to OUR defaults. Opc.Ua.Server 1.5.378.182 flipped the SDK default of
// TreatUncertainAsBad to true; history-read aggregates (Sql.Common evaluators) are fixed at false, so the live
// and historical paths must agree and stay behaviour-neutral across the SDK hop (lmxopcua#782).
var defaults = manager.GetDefaultConfiguration(NodeId.Null) ?? new AggregateConfiguration();
defaults.TreatUncertainAsBad = ServerAggregateConfiguration.TreatUncertainAsBad;
defaults.PercentDataBad = ServerAggregateConfiguration.PercentDataBad;
defaults.PercentDataGood = ServerAggregateConfiguration.PercentDataGood;
defaults.UseSlopedExtrapolation = ServerAggregateConfiguration.UseSlopedExtrapolation;
manager.SetDefaultConfiguration(defaults);
await Compatibility.Aggregates.CompatibilityAggregateFactory.RegisterAsync(manager, cancellationToken).ConfigureAwait(false);
_otOpcUaNodeManager?.SyncAdvertisedAggregates();
return manager;
}
catch
{
manager.Dispose();
throw;
}
}
/// <summary>
/// The <c>Server.ServiceLevel</c> a node advertises from the moment its endpoint accepts sessions until the
/// redundancy layer publishes a real level (lmxopcua#885): <c>0</c>, the design's Down / Detached tier
/// (<c>ServiceLevelCalculator</c> returns 0 for a member that is not Up/Joining, and a node that has not yet
/// received its first redundancy snapshot has no role). The SDK starts the value at 255 — full service — so
/// a restarting pair node out-ranked the real Primary (250) for the ~10 s it took to join. Below the SDK's
/// 200 floor, so the session-headroom calculator never lifts it either.
/// </summary>
public const byte StartupServiceLevel = 0;
private OpcUaRedundancyMode _redundancyMode = OpcUaRedundancyMode.Unset;
private string _selfUri = string.Empty;
private string[] _peerUris = [];
private WarmStandbyState _standby = WarmStandbyState.Off;
/// <summary>The redundancy mode configured before start (Gitea #717).</summary>
public OpcUaRedundancyMode RedundancyMode => _redundancyMode;
/// <summary>The Warm standby flags shared with the node manager.</summary>
internal WarmStandbyState Standby => _standby;
/// <summary>The initial <c>Server.ServiceLevel</c> under <c>Warm</c> (spec §4.3: the NoData band, replacing the
/// SDK's 255 and this server's #885 value 0 until the first computed level).</summary>
public const byte WarmBootServiceLevel = 1;
/// <summary>
/// Sets the startup-static redundancy metadata (Gitea #717 spec §3) before <c>StartAsync</c>.
/// <see cref="OpcUaRedundancyMode.Unset"/> (the default when this is never called) leaves the SDK graph and
/// every data path exactly as they are today.
/// </summary>
/// <param name="mode">The validated mode.</param>
/// <param name="effectiveSelfUri">The effective <c>ApplicationConfiguration.ApplicationUri</c>.</param>
/// <param name="peerUris">The peer URIs, in configured order.</param>
public void ConfigureRedundancy(OpcUaRedundancyMode mode, string effectiveSelfUri, IReadOnlyList<string> peerUris)
{
if (_otOpcUaNodeManager is not null)
throw new InvalidOperationException("Redundancy must be configured before the server starts.");
_redundancyMode = mode;
_selfUri = effectiveSelfUri;
_peerUris = peerUris.ToArray();
_standby = new WarmStandbyState(mode == OpcUaRedundancyMode.Warm);
}
/// <summary>
/// The data-plane transition steps a Warm <c>OpcUaPublishActor</c> drives (spec §4.7), or null when the server
/// is not Warm or has not started.
/// </summary>
/// <returns>The projection, or null.</returns>
public IStandbyProjection? CreateStandbyProjection() =>
_standby.WarmMode && _otOpcUaNodeManager is { } nm ? new SdkStandbyProjection(nm, _standby) : null;
/// <summary>Test seam: ids of the live subscriptions, for the decision record's dead-subscription sweep.</summary>
private IReadOnlySet<uint> LiveSubscriptionIds()
{
var ids = new HashSet<uint>();
try
{
if (CurrentInstance?.SubscriptionManager is { } manager)
foreach (var subscription in manager.GetSubscriptions()) ids.Add(subscription.Id);
}
catch (Exception)
{
// Shutdown race: an empty set only drops records, which re-decide (fail-safe) at their next delivery.
}
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 />
public override async ValueTask<PublishResponse> PublishAsync(SecureChannelContext secureChannelContext,
RequestHeader? requestHeader, ArrayOf<SubscriptionAcknowledgement> subscriptionAcknowledgements,
RequestLifetime requestLifetime)
{
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)
{
response.NotificationMessage = Decide(record, response.SubscriptionId, message);
var available = new List<uint>(response.AvailableSequenceNumbers.Count);
for (var i = 0; i < response.AvailableSequenceNumbers.Count; i++) available.Add(response.AvailableSequenceNumbers[i]);
record.Prune(response.SubscriptionId, available, message.SequenceNumber);
}
if (Interlocked.Increment(ref _publishesSinceSweep) % 1024 == 0) record.SweepDead(LiveSubscriptionIds());
return response;
}
/// <inheritdoc />
public override async ValueTask<RepublishResponse> RepublishAsync(SecureChannelContext secureChannelContext,
RequestHeader? requestHeader, uint subscriptionId, uint retransmitSequenceNumber, RequestLifetime requestLifetime)
{
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!;
}
/// <summary>The recorded (or, first time, current) decision for one delivery, applied to the SDK's fresh clone.</summary>
private NotificationMessage Decide(FirstDeliveryRecord record, uint subscriptionId, NotificationMessage message)
{
if (!record.Decide(subscriptionId, message.SequenceNumber)) return message;
var projected = StandbyNotificationRewriter.Project(message, out var rewritten);
if (rewritten > 0)
{
ZB.MOM.WW.OtOpcUa.Commons.Observability.OtOpcUaTelemetry.StandbyProjectedNotifications.Add(rewritten);
}
return projected;
}
/// <summary>
/// Installs the standard redundancy metadata (Gitea #717 spec §3, T0a): under <c>Warm</c>
/// <c>Server.ServerRedundancy</c> becomes a <c>NonTransparentRedundancyType</c> whose read-only
/// <c>ServerUriArray</c> (<c>i=11314</c>) is <c>[self, peers…]</c>, <c>RedundancySupport</c> is <c>Warm</c> and
/// ServiceLevel boots at <see cref="WarmBootServiceLevel"/>; under <c>None</c> <c>RedundancySupport</c> is
/// <c>None</c> and the SDK's orphan <c>i=11314</c> is deleted, so it is absent by NodeId as well as by browse.
/// <c>Unset</c> touches nothing.
/// </summary>
private async ValueTask InstallRedundancyMetadataAsync(IServerInternal server, CancellationToken cancellationToken)
{
if (_redundancyMode == OpcUaRedundancyMode.Unset) return;
var serverObject = server.ServerObject
?? throw new InvalidOperationException("The Server object is unavailable during server startup.");
var context = server.DefaultSystemContext;
var redundancy = serverObject.ServerRedundancy
?? throw new InvalidOperationException("Server.ServerRedundancy is unavailable during server startup.");
if (_redundancyMode == OpcUaRedundancyMode.None)
{
redundancy.RedundancySupport!.Value = RedundancySupport.None;
redundancy.RedundancySupport.ClearChangeMasks(context, false);
// T0a finding: the SDK's predefined i=11314 survives as an orphan (unreferenced, but Good [] by NodeId).
if (server.DiagnosticsNodeManager is AsyncCustomNodeManager diagnostics)
await diagnostics.DeleteNodeAsync(context, VariableIds.Server_ServerRedundancy_ServerUriArray, cancellationToken)
.ConfigureAwait(false);
return;
}
var replacer = server.DiagnosticsNodeManager as IPredefinedNodeSubtypeReplacer
?? throw new InvalidOperationException("The diagnostics node manager cannot replace predefined node subtypes.");
var replaced = (NonTransparentRedundancyState)await replacer.ReplacePredefinedInstanceSubtypeAsync(context, redundancy,
context.CreateInstanceOfNonTransparentRedundancyType(),
new Dictionary<QualifiedName, NodeId>
{
[new QualifiedName(BrowseNames.ServerUriArray, 0)] = VariableIds.Server_ServerRedundancy_ServerUriArray,
},
node => serverObject.ServerRedundancy = (ServerRedundancyState)node, cancellationToken).ConfigureAwait(false);
replaced.RedundancySupport!.Value = RedundancySupport.Warm;
replaced.ServerUriArray!.Value = (ArrayOf<string>)new[] { _selfUri }.Concat(_peerUris).ToArray();
replaced.ServerUriArray.AccessLevel = replaced.ServerUriArray.UserAccessLevel = AccessLevels.CurrentRead;
replaced.ClearChangeMasks(context, true);
if (serverObject.ServiceLevel is { } serviceLevel)
{
serviceLevel.Value = WarmBootServiceLevel;
serviceLevel.Timestamp = DateTime.UtcNow;
serviceLevel.ClearChangeMasks(context, includeChildren: false);
}
}
/// <inheritdoc />
protected override async ValueTask OnNodeManagerStartedAsync(
IServerInternal server, CancellationToken cancellationToken = default)
{
await base.OnNodeManagerStartedAsync(server, cancellationToken).ConfigureAwait(false);
// Runs after CreateServerObjectAsync wrote the SDK's 255 and before the server goes Running, so no session can
// ever read 255. SdkServiceLevelPublisher claims the value once the host binds and replays any level the
// redundancy layer already requested; until one is requested this value stands.
if (server.ServerObject?.ServiceLevel is { } serviceLevel)
{
serviceLevel.Value = StartupServiceLevel;
serviceLevel.Timestamp = DateTime.UtcNow;
serviceLevel.ClearChangeMasks(server.DefaultSystemContext, includeChildren: false);
}
await InstallRedundancyMetadataAsync(server, cancellationToken).ConfigureAwait(false);
var auditType = server.DiagnosticsNodeManager?
.FindPredefinedNode<BaseObjectTypeState>(ObjectTypeIds.AuditWriteUpdateEventType)
?? throw new InvalidOperationException("AuditWriteUpdateEventType is unavailable during server startup.");
_otOpcUaNodeManager!.InstallApplicationAuditPermissions(auditType);
}
/// <summary>
/// Test/measurement switch (Gitea #870): false makes servers started afterwards use the SDK's own event queues, so
/// the perf harness can A/B the two in one process. Never cleared in production.
/// </summary>
internal static bool RingEventQueues { get; set; } = true;
/// <summary>
/// The SDK's factory with event queues swapped for <see cref="RingEventMonitoredItemQueue"/> (Gitea #870: since #855
/// folder event items are queued under <c>Lock</c>, and the SDK queue's discard-oldest is an O(QueueSize) shift).
/// A factory set through <see cref="StandardServer.MonitoredItemQueueFactory"/> is used as-is.
/// </summary>
/// <inheritdoc />
protected override IMonitoredItemQueueFactory? CreateMonitoredItemQueueFactory(
IServerInternal server, ApplicationConfiguration configuration)
{
var factory = base.CreateMonitoredItemQueueFactory(server, configuration);
if (factory is null || ReferenceEquals(factory, MonitoredItemQueueFactory) || !RingEventQueues) return factory;
// Server-owned (OwnsMonitoredItemQueueFactory: not the property's instance), so disposed on stop with the SDK's.
return new RingEventQueueFactory(factory);
}
/// <inheritdoc />
protected override MasterNodeManager CreateMasterNodeManager(
IServerInternal server, ApplicationConfiguration configuration)
{
_otOpcUaNodeManager = new OtOpcUaNodeManager(server, configuration, _nodeManagerLogger, _standby);
return new MasterNodeManager(server, configuration, dynamicNamespaceUri: null, _otOpcUaNodeManager);
}
}