e61db01686
S3: the SDK installs a new identity object on every ActivateSession (decompiled Opc.Ua.Server 2.0.1: Session.UpdateUserIdentity assigns EffectiveIdentity; MonitoredItem/Subscription.EffectiveIdentity read the current session's), so an object-keyed admission forgot a re-activated or transferred session. Admission is now keyed on RoleCarryingUserIdentity.AdmissionKey (principal + api key id), and a removal also tells an item that passes the current gate (uncached). S4: the per-condition record is a lazily allocated locked HashSet<string> (no ConditionalWeakTable per condition), one entry per credential, capped at 1024, dropped after the removal's RefreshRequired is decided. N4: Verdict writes back only while that instance is still live. Tests: OI re-activation (red on revert), unit S3/S4 + N4 (red on revert); docs. Also DataConnections.md for #933 r1 S1/S2.
863 lines
51 KiB
C#
863 lines
51 KiB
C#
using System.Collections.Concurrent;
|
||
using Microsoft.Extensions.Logging;
|
||
using Opc.Ua;
|
||
using Opc.Ua.Server;
|
||
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.OpcUaServer.Security;
|
||
using ReferenceEqualityComparer = System.Collections.Generic.ReferenceEqualityComparer;
|
||
|
||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||
|
||
/// <summary>
|
||
/// A3 (plan §5.3): one imported condition — its node, identity (connection, condition_key), current placements and the
|
||
/// projected folders it is wired into right now. Mutated only under the node manager's <c>Lock</c>.
|
||
/// </summary>
|
||
internal sealed class ImportedCondition(AlarmConditionState alarm, string connectionId, string conditionKey)
|
||
{
|
||
public AlarmConditionState Alarm { get; } = alarm;
|
||
public string ConnectionId { get; } = connectionId;
|
||
public string ConditionKey { get; } = conditionKey;
|
||
private IReadOnlyList<ImportedConditionPlacement> _placements = [];
|
||
private long _supportedMethods = -1;
|
||
|
||
/// <summary>Written under <c>Lock</c>; read without it by A3b methods (review N8: a volatile publication of an immutable list).</summary>
|
||
public IReadOnlyList<ImportedConditionPlacement> Placements
|
||
{
|
||
get => Volatile.Read(ref _placements);
|
||
set => Volatile.Write(ref _placements, value);
|
||
}
|
||
public HashSet<FolderState> Folders { get; } = new(ReferenceEqualityComparer.Instance);
|
||
/// <summary>NIT (review r1): an immutable copy of <see cref="Folders"/> for the delivery paths that read off <c>Lock</c>.</summary>
|
||
public FolderState[] WiredFolders { get; set; } = [];
|
||
/// <summary>The last origin record applied (state known), re-applied with another Quality on staleness.</summary>
|
||
public AlarmConditionSnapshot? Last { get; set; }
|
||
/// <summary>The marker of the latest applied record. Written under <see cref="MethodGate"/> (A3b reads it without <c>Lock</c>).</summary>
|
||
public DataActivationMarker? Activation { get; set; }
|
||
/// <summary>N6: consumer-minted EventIds of this condition's recent events → the activation marker each described.
|
||
/// Mutated and read under <see cref="MethodGate"/>.</summary>
|
||
public LinkedList<(ByteString EventId, DataActivationMarker? Activation)> RecentEvents { get; } = new();
|
||
/// <summary>A3b (§5.6 step 2): the small EventId registry's own lock — a remote method resolves its EventId and the current
|
||
/// marker under it, never under the node manager's <c>Lock</c>.</summary>
|
||
public object MethodGate { get; } = new();
|
||
/// <summary>The origin's <c>supported_methods</c> for the service principal (null until a listing carried it).</summary>
|
||
/// <remarks>Review N8: read without <c>Lock</c> by A3b methods — stored as one atomic 64-bit word (-1 = not listed yet).</remarks>
|
||
public uint? SupportedMethods
|
||
{
|
||
get => Interlocked.Read(ref _supportedMethods) is var v && v >= 0 ? (uint)v : null;
|
||
set => Interlocked.Exchange(ref _supportedMethods, value is { } m ? m : -1);
|
||
}
|
||
/// <summary>The <c>time</c> of the latest applied record (N6/F6: re-binding requires it unchanged).</summary>
|
||
public DateTimeOffset? LastTime { get; set; }
|
||
/// <summary>Bumped on every placement change (verdict caches key on it).</summary>
|
||
public long PlacementVersion { get; set; }
|
||
/// <summary>Native (driver-fed) at the origin: Confirm / shelve / enable have no upstream path.</summary>
|
||
public bool IsNative { get; init; }
|
||
|
||
/// <summary>
|
||
/// #936: the credentials (<see cref="RoleCarryingUserIdentity.AdmissionKey"/>: principal + key id) that passed the §5.4
|
||
/// gate for THIS condition instance — each delivery, refresh replay and Read/Browse of it is gated, so any client that
|
||
/// may hold it is here. Lets the removal RefreshRequired reach the holders even after the mapping that admitted them
|
||
/// left the deployed set (the current gate then admits nobody).
|
||
/// Review r1 S3: keyed on the credential, not the identity OBJECT — the SDK installs a new identity object on every
|
||
/// ActivateSession (verified: <c>Session.UpdateUserIdentity</c> assigns <c>EffectiveIdentity</c>, and
|
||
/// <c>MonitoredItem.EffectiveIdentity</c> reads it through the subscription's CURRENT session), so a re-activated or
|
||
/// transferred session would otherwise be forgotten.
|
||
/// Review r1 S4: allocated on the first admission only (most conditions are never admitted to anyone), a plain locked
|
||
/// set of strings shared with the identity — no finalizable containers, no dependent handles. Bounded: one entry per
|
||
/// distinct credential admitted (≤ deployed API keys + anonymous; NOT per session — a Server-object ConditionRefresh by
|
||
/// S sessions of K keys adds ≤ C × K entries), capped at <see cref="MaxAdmittedCredentials"/>; past the cap a holder
|
||
/// falls back to the current gate at removal. Dropped when the condition is removed.
|
||
/// </summary>
|
||
private HashSet<string>? _admitted;
|
||
|
||
/// <summary>#936 review r1 S4: the per-condition cap on recorded credentials (far above any real key count).</summary>
|
||
internal const int MaxAdmittedCredentials = 1024;
|
||
|
||
public void Admit(RoleCarryingUserIdentity identity)
|
||
{
|
||
var set = Volatile.Read(ref _admitted);
|
||
if (set is null)
|
||
{
|
||
var fresh = new HashSet<string>(StringComparer.Ordinal);
|
||
set = Interlocked.CompareExchange(ref _admitted, fresh, null) ?? fresh;
|
||
}
|
||
lock (set) if (set.Count < MaxAdmittedCredentials) set.Add(identity.AdmissionKey);
|
||
}
|
||
|
||
public bool WasAdmitted(object? identity)
|
||
{
|
||
if (identity is not RoleCarryingUserIdentity caller || Volatile.Read(ref _admitted) is not { } set) return false;
|
||
lock (set) return set.Contains(caller.AdmissionKey);
|
||
}
|
||
|
||
/// <summary>Test/diagnostic observation: credentials recorded (0 when never admitted — the set is not allocated).</summary>
|
||
internal int AdmittedCount { get { var set = Volatile.Read(ref _admitted); if (set is null) return 0; lock (set) return set.Count; } }
|
||
internal bool AdmittedAllocated => Volatile.Read(ref _admitted) is not null;
|
||
|
||
/// <summary>#936 review r1 S4: the removal's RefreshRequired has been decided — the record goes with the instance.</summary>
|
||
public void ForgetAdmitted() => Volatile.Write(ref _admitted, null);
|
||
}
|
||
|
||
/// <summary>
|
||
/// A3: what a consumer-minted EventId of an imported condition resolves to — the seam remote condition methods (A3b, §5.6)
|
||
/// dispatch through: the connection, the origin's opaque key, the PRIMARY placement (the address the origin resolves), and
|
||
/// the activation marker of the event the client saw.
|
||
/// </summary>
|
||
public sealed record ImportedConditionBinding(string ConnectionId, string ConditionKey, ImportedConditionPlacement Primary,
|
||
IReadOnlyList<ImportedConditionPlacement> Placements, DataActivationMarker? Activation, bool IsNative);
|
||
|
||
/// <summary>
|
||
/// A3 (plan §5.3, N7): the consumer's imported-condition registry, keyed by FULL NodeId in the
|
||
/// <c>https://zb.com/otopcua/mapped/conditions</c> namespace. Imported conditions never enter the realm-keyed maps
|
||
/// (<c>_alarmConditions</c> and friends). Mutated only under the node manager's <c>Lock</c>; <see cref="IsLive"/> and
|
||
/// <see cref="Find"/> are lock-free reads.
|
||
/// </summary>
|
||
internal sealed class ProjectedConditionRegistry
|
||
{
|
||
/// <summary>
|
||
/// Recent EventIds kept per condition (§5.6 step 3: "within its last N (default 8) events"). A3 review round 2: back to
|
||
/// the plan's 8 — A3a's 32 had no recorded need (validity is "minted under the current marker", which only the newest
|
||
/// few can satisfy; an older EventId already answers <c>BadEventIdUnknown</c> at the origin).
|
||
/// </summary>
|
||
internal const int RecentEventIds = 8;
|
||
|
||
private readonly ConcurrentDictionary<NodeId, ImportedCondition> _byNode = new();
|
||
private readonly ConcurrentDictionary<AlarmConditionState, ImportedCondition> _byInstance = new(ReferenceEqualityComparer.Instance);
|
||
/// <summary>(mapping, folder local subject) → conditions placed there (wired or waiting for the folder to materialise).</summary>
|
||
internal readonly Dictionary<(string Mapping, string Subject), HashSet<NodeId>> ByFolderKey = new();
|
||
/// <summary>Projected folder node → the folder INSTANCE promoted for it and the conditions wired into it (review r1 S1: a
|
||
/// re-created folder with the same NodeId is a different notifier and is promoted afresh).</summary>
|
||
internal readonly Dictionary<NodeId, (FolderState Folder, HashSet<NodeId> Conditions)> WiredByFolder = new();
|
||
/// <summary>Review r1 S5: (mapping, local subject) → projected folder NodeId, maintained incrementally (was a scan of every
|
||
/// projected node per apply chunk); resolved against the live projected maps at use.</summary>
|
||
internal readonly Dictionary<(string Mapping, string Subject), NodeId> FolderIds = new();
|
||
internal readonly Dictionary<NodeId, (string Mapping, string Subject)> FolderKeys = new();
|
||
/// <summary>Deviation 3: projected folders of condition-bearing mappings, event notifiers from materialisation.</summary>
|
||
internal readonly HashSet<NodeId> PromotedFolders = new();
|
||
/// <summary>Review r1 S2: a positive verdict is re-proved at least this often (credential expiry is honoured exactly).</summary>
|
||
internal static readonly TimeSpan PositiveVerdictTtl = TimeSpan.FromSeconds(5);
|
||
private readonly object _verdictGate = new();
|
||
private readonly Dictionary<(object Identity, NodeId Condition), (long Generation, long PlacementVersion, bool Allowed, DateTimeOffset ValidUntil)> _verdicts = new();
|
||
|
||
public int Count => _byNode.Count;
|
||
public IEnumerable<ImportedCondition> All => _byNode.Values;
|
||
public bool IsLive(NodeState node) => node is AlarmConditionState alarm && _byInstance.ContainsKey(alarm);
|
||
public ImportedCondition? Find(NodeState? node) =>
|
||
node is AlarmConditionState alarm && _byInstance.TryGetValue(alarm, out var c) ? c : null;
|
||
public ImportedCondition? Find(NodeId id) => _byNode.TryGetValue(id, out var c) ? c : null;
|
||
public bool IsWiredTo(ImportedCondition condition, NodeState notifier) =>
|
||
notifier is FolderState folder && Array.IndexOf(condition.WiredFolders, folder) >= 0 && _byInstance.ContainsKey(condition.Alarm);
|
||
|
||
public void Add(ImportedCondition condition)
|
||
{
|
||
_byNode[condition.Alarm.NodeId] = condition;
|
||
_byInstance[condition.Alarm] = condition;
|
||
}
|
||
|
||
public void Remove(ImportedCondition condition)
|
||
{
|
||
_byNode.TryRemove(condition.Alarm.NodeId, out _);
|
||
_byInstance.TryRemove(condition.Alarm, out _);
|
||
foreach (var key in condition.Placements.Select(FolderKey).Distinct())
|
||
if (ByFolderKey.TryGetValue(key, out var set) && set.Remove(condition.Alarm.NodeId) && set.Count == 0) ByFolderKey.Remove(key);
|
||
lock (_verdictGate)
|
||
foreach (var stale in _verdicts.Keys.Where(k => k.Condition == condition.Alarm.NodeId).ToList()) _verdicts.Remove(stale);
|
||
}
|
||
|
||
public static (string, string) FolderKey(ImportedConditionPlacement p) => (p.MappingId, p.FolderLocalSubject);
|
||
|
||
/// <summary>
|
||
/// The §5.4 verdict, cached per (identity, condition, authority generation, placement version). Review r1 S2: a positive
|
||
/// verdict also carries the caller's credential expiry and a short TTL — a Server-object item has no other revalidation,
|
||
/// so an expired key (or anything the generation does not capture) is never served from cache past either.
|
||
/// </summary>
|
||
public bool Verdict(object identity, ImportedCondition condition, long generation, DateTimeOffset now, DateTimeOffset? credentialExpires,
|
||
Func<bool> compute)
|
||
{
|
||
var key = (identity, condition.Alarm.NodeId);
|
||
lock (_verdictGate)
|
||
{
|
||
if (_verdicts.TryGetValue(key, out var cached) && cached.Generation == generation && cached.PlacementVersion == condition.PlacementVersion
|
||
&& now < cached.ValidUntil)
|
||
return cached.Allowed;
|
||
}
|
||
var allowed = compute();
|
||
var validUntil = !allowed ? DateTimeOffset.MaxValue
|
||
: credentialExpires is { } expires && expires < now + PositiveVerdictTtl ? expires : now + PositiveVerdictTtl;
|
||
lock (_verdictGate)
|
||
{
|
||
// #936 review r1 N4: computed off the gate — a Remove may have purged this NodeId's verdicts meanwhile. Written back
|
||
// only while THIS instance is still the live one (Remove drops it from _byInstance before purging under this gate),
|
||
// so a same-NodeId re-creation never inherits a verdict computed for the removed instance.
|
||
if (!_byInstance.ContainsKey(condition.Alarm)) return allowed;
|
||
if (_verdicts.Count >= 65_536) _verdicts.Clear(); // bounded: a flood of identities only costs recomputation
|
||
_verdicts[key] = (generation, condition.PlacementVersion, allowed, validUntil);
|
||
}
|
||
return allowed;
|
||
}
|
||
}
|
||
|
||
public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
|
||
{
|
||
/// <summary>Most imported updates applied per <c>Lock</c> hold (bounded Lock holds, A1 lessons).</summary>
|
||
internal const int ImportedApplyChunk = 128;
|
||
|
||
private readonly ProjectedConditionRegistry _importedConditions = new();
|
||
private readonly ConcurrentDictionary<IEventMonitoredItem, IDisposable> _importedEventDemand = new();
|
||
private long _importedEventsReported, _importedRefreshRequired;
|
||
|
||
/// <summary>A3: the consumer's condition gate + demand (null on a node with no data connections).</summary>
|
||
public IProjectedConditionAccess? ProjectedConditionAccess { get; set; }
|
||
|
||
/// <summary>Whether any imported condition is materialised (the publish rewriter's fast exit).</summary>
|
||
internal bool HasImportedConditions => _importedConditions.Count > 0;
|
||
|
||
/// <summary>Imported conditions currently materialised (test/diagnostic observation).</summary>
|
||
internal int ImportedConditionCount => _importedConditions.Count;
|
||
|
||
/// <summary>Imported condition events reported (one per genuine origin transition).</summary>
|
||
internal long ImportedEventsReported => Interlocked.Read(ref _importedEventsReported);
|
||
|
||
/// <summary>How many N6 EventId slots a condition holds (test/diagnostic observation, the L2 harness).</summary>
|
||
internal int FindImportedConditionRecentEventCount(string connectionId, string conditionKey)
|
||
{
|
||
if (_importedConditions.Find(ImportedConditionNodeId(connectionId, conditionKey)) is not { } c) return 0;
|
||
lock (c.MethodGate) return c.RecentEvents.Count;
|
||
}
|
||
|
||
/// <summary>RefreshRequired events queued for imported conditions.</summary>
|
||
internal long ImportedRefreshRequiredQueued => Interlocked.Read(ref _importedRefreshRequired);
|
||
|
||
/// <summary>
|
||
/// A3 (§5.2 N4): whether <paramref name="nodeId"/> is in the imported-condition namespace. Every NodeId classifier
|
||
/// (authorizer, read, history, call) asks this BEFORE <see cref="RealmOf"/>, which would fold it into Uns.
|
||
/// </summary>
|
||
internal bool IsImportedConditionId(NodeId nodeId) =>
|
||
NamespaceIndexes.Count > 4 && nodeId.NamespaceIndex == NamespaceIndexes[4];
|
||
|
||
/// <summary>The imported-condition NodeId for (connection, condition_key) — never the mapping or placement (N4).</summary>
|
||
internal NodeId ImportedConditionNodeId(string connectionId, string conditionKey) =>
|
||
new(ImportedConditionIds.Identifier(connectionId, conditionKey), NamespaceIndexes[4]);
|
||
|
||
/// <summary>The imported condition an event is about (its snapshot handle, or an audit's SourceNode), or null.</summary>
|
||
private ImportedCondition? ImportedOf(IFilterTarget e)
|
||
{
|
||
if (_importedConditions.Count == 0) return null;
|
||
var node = ConditionOf(e);
|
||
if (_importedConditions.Find(node) is { } c) return c;
|
||
return node is BaseEventState { SourceNode.Value: { IsNull: false } source } && IsImportedConditionId(source)
|
||
? _importedConditions.Find(source)
|
||
: null;
|
||
}
|
||
|
||
/// <summary>
|
||
/// A3 (§5.4): the mapping gate (<c>CreateMonitoredItems</c> on ANY current placement mapping) for an item's identity,
|
||
/// REGARDLESS of <c>Security:Acl:Enabled</c>. No access wired / no role-carrying identity ⇒ false.
|
||
/// </summary>
|
||
private bool ImportedVisibleTo(IEventMonitoredItem item, ImportedCondition condition) =>
|
||
ImportedVisibleTo(item.EffectiveIdentity, condition);
|
||
|
||
private bool ImportedVisibleTo(object? identity, ImportedCondition condition)
|
||
{
|
||
if (ProjectedConditionAccess is not { } access || identity is not RoleCarryingUserIdentity caller) return false;
|
||
var generation = access.AuthorityGeneration;
|
||
var placements = condition.Placements;
|
||
return _importedConditions.Verdict(caller, condition, generation, DateTimeOffset.UtcNow, caller.CredentialExpiresUtc, () =>
|
||
{
|
||
var allowed = access.CanSee(caller, placements);
|
||
if (allowed) condition.Admit(caller); // #936: a cached positive verdict was computed (and recorded) here first
|
||
return allowed;
|
||
});
|
||
}
|
||
|
||
/// <summary>#936 review r1 S3: the current §5.4 gate, uncached (a removed instance's removal decision).</summary>
|
||
private bool ImportedVisibleNow(object identity, ImportedCondition condition) =>
|
||
ProjectedConditionAccess is { } access && identity is RoleCarryingUserIdentity caller && access.CanSee(caller, condition.Placements);
|
||
|
||
/// <summary>The marker a queued imported event carries: re-checked at every Publish and Republish (§5.4).</summary>
|
||
private ProjectedEventMarker ImportedMarker(IEventMonitoredItem item, ImportedCondition condition)
|
||
{
|
||
var identity = item.EffectiveIdentity;
|
||
var generation = ProjectedConditionAccess?.AuthorityGeneration ?? 0;
|
||
return new ProjectedEventMarker(identity, condition.Alarm.NodeId, generation,
|
||
() => _importedConditions.IsLive(condition.Alarm) && ImportedVisibleTo(identity, condition));
|
||
}
|
||
|
||
/// <summary>Imported-condition events always take the marked path, whatever <see cref="UseProjectedEventDelivery"/> says.</summary>
|
||
private void QueueImportedToItem(IEventMonitoredItem item, IFilterTarget e, ImportedCondition condition)
|
||
{
|
||
var cache = e is ConditionEventSnapshot snapshot ? snapshot.DeliveryCache : new EventDeliveryCache();
|
||
if (cache.QueueMarked(Server, item, e, i => ImportedMarker(i, condition))) Interlocked.Increment(ref _projectedDeliveries);
|
||
}
|
||
|
||
/// <summary>
|
||
/// §5.4: the publish-time gate for an UNMARKED list (a select-clause modify rebuilt it). Null when the list is not an
|
||
/// imported-condition event; otherwise the gate re-evaluated for the publishing session.
|
||
/// </summary>
|
||
internal bool? ReevaluateImportedEvent(EventFieldList list, object? identity)
|
||
{
|
||
if (list.Handle is not InstanceStateSnapshot { Handle: ConditionState condition } || !IsImportedConditionId(condition.NodeId))
|
||
return null;
|
||
return _importedConditions.Find(condition.NodeId) is { } live && ReferenceEquals(live.Alarm, condition)
|
||
&& ImportedVisibleTo(identity, live);
|
||
}
|
||
|
||
/// <summary>
|
||
/// A3 (§5.4): the authorizer's classifier for an imported-condition id (or a child of one): Browse / Read /
|
||
/// CreateMonitoredItems are allowed when the caller passes the mapping gate on any placement; everything else
|
||
/// (Call — A3b, HistoryRead, writes) is refused here.
|
||
/// </summary>
|
||
internal bool AuthorizeImportedCondition(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId)
|
||
{
|
||
if (operation is not (OpcUaOperation.Browse or OpcUaOperation.Read or OpcUaOperation.CreateMonitoredItems)) return false;
|
||
if (!nodeId.TryGetValue(out string identifier)
|
||
|| !ImportedConditionIds.TryParse(identifier, out var conditionIdentifier, out _, out _, out _)) return false;
|
||
var condition = _importedConditions.Find(new NodeId(conditionIdentifier, nodeId.NamespaceIndex));
|
||
return condition is not null && ImportedVisibleTo(identity, condition);
|
||
}
|
||
|
||
/// <summary>
|
||
/// A3b seam (§5.6, N6): resolves an imported condition NodeId and a consumer-minted EventId to its connection, origin
|
||
/// key, primary placement and the activation marker the event described. False for an unknown condition or EventId.
|
||
/// </summary>
|
||
public bool TryResolveImportedEvent(NodeId conditionId, ByteString eventId, out ImportedConditionBinding? binding)
|
||
{
|
||
binding = null;
|
||
if (_importedConditions.Find(conditionId) is not { Placements.Count: > 0 } c) return false;
|
||
lock (c.MethodGate)
|
||
{
|
||
foreach (var (id, activation) in c.RecentEvents)
|
||
{
|
||
if (id != eventId) continue;
|
||
binding = new(c.ConnectionId, c.ConditionKey, c.Placements[0], c.Placements, activation, c.IsNative);
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------------------------------------------------
|
||
// IProjectedConditionSink
|
||
// ---------------------------------------------------------------------------------------------------------------------
|
||
|
||
/// <inheritdoc />
|
||
public void ApplyConditions(IReadOnlyList<ImportedConditionUpdate> updates)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(updates);
|
||
EnsureAddressSpaceCreated();
|
||
var unbindable = new List<ImportedCondition>();
|
||
for (var start = 0; start < updates.Count; start += ImportedApplyChunk)
|
||
{
|
||
lock (Lock)
|
||
{
|
||
if (_disposing) return;
|
||
for (var i = start; i < Math.Min(updates.Count, start + ImportedApplyChunk); i++)
|
||
{
|
||
try { if (ApplyImported(updates[i]) is { } c) unbindable.Add(c); }
|
||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or ServiceResultException)
|
||
{
|
||
_logger.LogWarning(ex, "OtOpcUaNodeManager: imported condition update refused (connection {Connection})",
|
||
updates[i].ConnectionId);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
// N6 (G4 step 3): a resync that left retained EventIds un-re-bindable ⇒ RefreshRequired, outside Lock — only to the
|
||
// items that may see one of THOSE conditions (A3b open item, review r1).
|
||
if (unbindable.Count > 0) QueueImportedRefresh(unbindable);
|
||
}
|
||
|
||
/// <inheritdoc />
|
||
public void RemoveConditions(string connectionId, IReadOnlyCollection<string> conditionKeys)
|
||
{
|
||
var keys = conditionKeys.ToArray();
|
||
var removed = new List<ImportedCondition>();
|
||
var targets = new RefreshTargets();
|
||
for (var start = 0; start < keys.Length; start += ImportedApplyChunk)
|
||
{
|
||
lock (Lock)
|
||
{
|
||
var chunk = new List<ImportedCondition>();
|
||
foreach (var key in keys.Skip(start).Take(ImportedApplyChunk))
|
||
{
|
||
if (!ImportedConditionIds.IsWellFormedConditionKey(key)) continue;
|
||
if (_importedConditions.Find(ImportedConditionNodeId(connectionId, key)) is { } c) chunk.Add(c);
|
||
}
|
||
// Deviation 6 (review r1): who may have been holding these conditions is captured BEFORE they are unwired.
|
||
CollectRefreshTargets(chunk, targets);
|
||
foreach (var c in chunk) RemoveImported(c);
|
||
removed.AddRange(chunk);
|
||
}
|
||
}
|
||
// §5.2 "removal + RefreshRequired": a client holding a removed (e.g. Active/Retain) condition is told to refresh, after
|
||
// which it no longer lists it. Outside Lock. #936: decided by who was ADMITTED to the condition, not by the current
|
||
// mapping set — a removal caused by the mapping (or its connection) leaving the deployed set must still tell them.
|
||
if (removed.Count > 0)
|
||
{
|
||
QueueRefreshRequired(targets, removed, removal: true);
|
||
foreach (var c in removed) c.ForgetAdmitted();
|
||
}
|
||
}
|
||
|
||
/// <inheritdoc />
|
||
public void MarkConnectionStale(string connectionId) =>
|
||
MarkStale(_importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList());
|
||
|
||
/// <inheritdoc />
|
||
public void MarkConditionsStale(string connectionId, IReadOnlyCollection<string> conditionKeys) =>
|
||
MarkStale(conditionKeys.Where(ImportedConditionIds.IsWellFormedConditionKey)
|
||
.Select(key => _importedConditions.Find(ImportedConditionNodeId(connectionId, key))).OfType<ImportedCondition>().ToList());
|
||
|
||
private void MarkStale(List<ImportedCondition> targets)
|
||
{
|
||
for (var start = 0; start < targets.Count; start += ImportedApplyChunk)
|
||
{
|
||
lock (Lock)
|
||
{
|
||
foreach (var c in targets.Skip(start).Take(ImportedApplyChunk))
|
||
{
|
||
if (!_importedConditions.IsLive(c.Alarm)) continue;
|
||
var stale = (c.Last ?? CurrentSnapshot(c.Alarm)) with { StatusCode = StatusCodes.BadNoCommunication.Code };
|
||
if (ApplyConditionState(c.Alarm, stale, UtcNow)) ReportImported(c, UtcNow);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <inheritdoc />
|
||
/// <remarks>
|
||
/// A connection with no materialised condition returns early: nothing of it can be held by a client (a removal tells
|
||
/// its own holders, captured before the removal — deviation 6, review r1).
|
||
/// </remarks>
|
||
public void RequireRefresh(string connectionId)
|
||
{
|
||
var conditions = _importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList();
|
||
if (conditions.Count > 0) QueueImportedRefresh(conditions);
|
||
}
|
||
|
||
/// <summary>Event items that may be holding imported conditions: the Server-object items, and each direct item with the
|
||
/// conditions wired at its notifier.</summary>
|
||
private sealed class RefreshTargets
|
||
{
|
||
public HashSet<IEventMonitoredItem> ServerItems { get; } = new(ReferenceEqualityComparer.Instance);
|
||
public Dictionary<IEventMonitoredItem, List<ImportedCondition>> Direct { get; } = new(ReferenceEqualityComparer.Instance);
|
||
}
|
||
|
||
/// <summary>Under Lock: the items that may see <paramref name="conditions"/> (bounded by the caller's chunk).</summary>
|
||
private void CollectRefreshTargets(IReadOnlyList<ImportedCondition> conditions, RefreshTargets targets)
|
||
{
|
||
if (conditions.Count == 0) return;
|
||
foreach (var item in _allEventsItems.Keys) targets.ServerItems.Add(item);
|
||
foreach (var c in conditions)
|
||
foreach (var folder in c.Folders)
|
||
if (MonitoredNodes.TryGetValue(folder.NodeId, out var monitored) && monitored.EventMonitoredItems is { } attached)
|
||
foreach (var item in attached.Values)
|
||
{
|
||
if (item is null) continue;
|
||
if (!targets.Direct.TryGetValue(item, out var list)) targets.Direct[item] = list = [];
|
||
list.Add(c);
|
||
}
|
||
}
|
||
|
||
/// <summary>Review r1 S5: the targets are gathered in 128-condition Lock holds; visibility is decided off Lock.</summary>
|
||
private void QueueImportedRefresh(IReadOnlyList<ImportedCondition> conditions)
|
||
{
|
||
var targets = new RefreshTargets();
|
||
for (var start = 0; start < conditions.Count; start += ImportedApplyChunk)
|
||
{
|
||
var chunk = conditions.Skip(start).Take(ImportedApplyChunk).ToList();
|
||
lock (Lock) CollectRefreshTargets(chunk, targets);
|
||
}
|
||
QueueRefreshRequired(targets, conditions);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Off Lock: one RefreshRequired per item that may see at least one of the conditions (§5.4 gate). For a
|
||
/// <paramref name="removal"/> (#936) the test is instead "its identity was admitted to the removed instance" — the
|
||
/// current gate cannot answer once the mapping is gone. The event carries no condition data (EventType
|
||
/// RefreshRequired, SourceNode = Server, SourceName "Server", Message "RefreshRequired", Severity Low), and it still
|
||
/// goes only to identities that could see the condition, so an ungranted session learns nothing.
|
||
/// </summary>
|
||
private void QueueRefreshRequired(RefreshTargets targets, IReadOnlyList<ImportedCondition> conditions, bool removal = false)
|
||
{
|
||
// #936 review r1 S3: admitted under this credential, OR passes the current gate now (a holder past the per-condition
|
||
// cap, or anything the record missed) — uncached, so no verdict is written back for the removed instance.
|
||
Func<IEventMonitoredItem, ImportedCondition, bool> holds = removal
|
||
? (item, c) => item.EffectiveIdentity is { } identity && (c.WasAdmitted(identity) || ImportedVisibleNow(identity, c))
|
||
: ImportedVisibleTo;
|
||
var send = new List<IEventMonitoredItem>();
|
||
foreach (var item in targets.ServerItems)
|
||
if (conditions.Any(c => holds(item, c))) send.Add(item);
|
||
foreach (var (item, candidates) in targets.Direct)
|
||
if (!targets.ServerItems.Contains(item) && candidates.Any(c => holds(item, c))) send.Add(item);
|
||
foreach (var item in send)
|
||
{
|
||
var e = new RefreshRequiredEventState(null);
|
||
e.Initialize(SystemContext, null, EventSeverity.Low, new LocalizedText("RefreshRequired"));
|
||
e.SetChildValue(SystemContext, BrowseNames.SourceNode, ObjectIds.Server, false);
|
||
e.SetChildValue(SystemContext, BrowseNames.SourceName, "Server", false);
|
||
item.QueueEvent(e);
|
||
Interlocked.Increment(ref _importedRefreshRequired);
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------------------------------------------------
|
||
// Materialise / apply / remove (under Lock)
|
||
// ---------------------------------------------------------------------------------------------------------------------
|
||
|
||
/// <returns>The condition when a resync left its retained EventIds un-re-bindable (the caller queues RefreshRequired).</returns>
|
||
private ImportedCondition? ApplyImported(ImportedConditionUpdate update)
|
||
{
|
||
var state = update.State;
|
||
if (update.Placements.Count == 0) throw new ArgumentException("An imported condition needs a placement.", nameof(update));
|
||
var id = ImportedConditionNodeId(update.ConnectionId, state.ConditionKey);
|
||
if (state.Removed)
|
||
{
|
||
if (_importedConditions.Find(id) is { } gone) RemoveImported(gone);
|
||
return null;
|
||
}
|
||
|
||
var condition = _importedConditions.Find(id);
|
||
if (condition is null)
|
||
{
|
||
var info = update.Info;
|
||
var name = string.IsNullOrWhiteSpace(info?.ConditionName) ? state.ConditionKey : info!.ConditionName;
|
||
var native = info?.SourceKind == DataConditionSourceKind.Native;
|
||
var type = info?.ConditionType is { } t && t.Contains("OffNormalAlarm", StringComparison.Ordinal) ? "OffNormalAlarm"
|
||
: info?.ConditionType is { } d && d.Contains("DiscreteAlarm", StringComparison.Ordinal) ? "DiscreteAlarm" : "AlarmCondition";
|
||
var alarm = CreateConditionNode(type, null, id, name, update.SourceName, (int)Math.Clamp(state.Severity, 1u, 1000u), native);
|
||
// A3a: no local apply of a remote method. Remote dispatch (claim / base.Call / await) is A3b (§5.6); until then
|
||
// every Part 9 method on an imported condition is refused before the SDK touches its state.
|
||
alarm.OnAcknowledge = (_, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported);
|
||
alarm.OnConfirm = (_, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported);
|
||
alarm.OnAddComment = (_, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported);
|
||
alarm.OnShelve = (_, _, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported);
|
||
alarm.OnTimedUnshelve = (_, _) => ServiceResult.Good;
|
||
alarm.OnEnableDisable = (_, _, _) => new ServiceResult(StatusCodes.BadNotSupported);
|
||
alarm.OnReportEvent = OnConditionReportEvent;
|
||
AddPredefinedNode(SystemContext, alarm);
|
||
condition = new ImportedCondition(alarm, update.ConnectionId, state.ConditionKey) { IsNative = native };
|
||
if (!state.StateKnown && alarm.Quality is not null)
|
||
{
|
||
// §5.1 T2: unknown at first sight ⇒ Uncertain, never "known inactive".
|
||
alarm.Quality.Value = StatusCodes.UncertainInitialValue;
|
||
}
|
||
_importedConditions.Add(condition);
|
||
}
|
||
|
||
UpdatePlacements(condition, update.Placements);
|
||
if (condition.Alarm.SourceName is { } sourceName) sourceName.Value = update.SourceName; // display only; rides the next event
|
||
if ((update.Info ?? state.Info) is { } listed) condition.SupportedMethods = listed.SupportedMethods;
|
||
|
||
// §5.1 T2: a record with state_known = false never changes the consumer's last state.
|
||
if (!state.StateKnown) return null;
|
||
var snapshot = new AlarmConditionSnapshot(state.Active, state.Acknowledged, state.Confirmed, state.Enabled,
|
||
Enum.IsDefined(typeof(AlarmShelvingKind), state.Shelving) ? (AlarmShelvingKind)state.Shelving : AlarmShelvingKind.Unshelved,
|
||
(ushort)Math.Clamp(state.Severity, 1u, 1000u), state.Message ?? "", state.Quality,
|
||
state.UnshelveAtUtc?.UtcDateTime,
|
||
Enum.IsDefined(typeof(AlarmConditionClass), state.ConditionClass) ? (AlarmConditionClass)state.ConditionClass : null);
|
||
var ts = state.TimeUtc?.UtcDateTime ?? UtcNow;
|
||
if (condition.Alarm.Comment is { } comment && state.Comment is not null) comment.Value = new LocalizedText(state.Comment);
|
||
if (condition.Alarm.ClientUserId is { } user && state.ClientUserId is not null) user.Value = state.ClientUserId;
|
||
var previous = condition.Activation;
|
||
var previousTime = condition.LastTime;
|
||
lock (condition.MethodGate) condition.Activation = state.Activation;
|
||
condition.Last = snapshot;
|
||
condition.LastTime = state.TimeUtc;
|
||
if (ApplyConditionState(condition.Alarm, snapshot, ts))
|
||
{
|
||
ReportImported(condition, ts);
|
||
return null;
|
||
}
|
||
return RebindImportedEventIds(condition, previous, previousTime, state) ? condition : null;
|
||
}
|
||
|
||
/// <summary>Reports one imported event (stamping a consumer-minted EventId, N6) through the shared reporter.</summary>
|
||
private void ReportImported(ImportedCondition condition, DateTime ts)
|
||
{
|
||
ReportConditionEvent(condition.Alarm, ts);
|
||
Interlocked.Increment(ref _importedEventsReported);
|
||
if (condition.Alarm.EventId?.Value is { } eventId)
|
||
{
|
||
lock (condition.MethodGate)
|
||
{
|
||
condition.RecentEvents.AddFirst((eventId, condition.Activation));
|
||
while (condition.RecentEvents.Count > ProjectedConditionRegistry.RecentEventIds) condition.RecentEvents.RemoveLast();
|
||
}
|
||
}
|
||
}
|
||
|
||
private void RemoveImported(ImportedCondition condition)
|
||
{
|
||
foreach (var folder in condition.Folders.ToList()) UnwireImportedFolder(condition, folder);
|
||
_importedConditions.Remove(condition);
|
||
TombstoneMonitoredSubtree(condition.Alarm, UtcNow);
|
||
ForgetPredefinedSubtree(condition.Alarm);
|
||
}
|
||
|
||
/// <summary>A snapshot of a node's current state (staleness before any known record arrived).</summary>
|
||
private static AlarmConditionSnapshot CurrentSnapshot(AlarmConditionState alarm) => new(
|
||
alarm.ActiveState?.Id?.Value == true, alarm.AckedState?.Id?.Value != false, alarm.ConfirmedState?.Id?.Value != false,
|
||
alarm.EnabledState?.Id?.Value != false, AlarmShelvingKind.Unshelved, (ushort)Math.Clamp((int)(alarm.Severity?.Value ?? 1), 1, 1000),
|
||
alarm.Message?.Value.Text ?? "", alarm.Quality?.Value.Code ?? StatusCodes.Good.Code);
|
||
|
||
// ---------------------------------------------------------------------------------------------------------------------
|
||
// Notifier wiring (N7): lazy, symmetric
|
||
// ---------------------------------------------------------------------------------------------------------------------
|
||
|
||
/// <summary>(mapping, local subject) → the live materialised projected folder (anchors included), or null. Under Lock.</summary>
|
||
private FolderState? FindProjectedFolder((string Mapping, string Subject) key)
|
||
{
|
||
if (!_importedConditions.FolderIds.TryGetValue(key, out var id)) return null;
|
||
if (_projectedAnchors.TryGetValue(id, out var anchor) && anchor.Node is FolderState a) return a;
|
||
return _projectedVariables.TryGetValue(id, out var entry) && entry.Node is FolderState f ? f : null;
|
||
}
|
||
|
||
private void UpdatePlacements(ImportedCondition condition, IReadOnlyList<ImportedConditionPlacement> placements)
|
||
{
|
||
var before = condition.Placements.Select(ProjectedConditionRegistry.FolderKey).ToHashSet();
|
||
var after = placements.Select(ProjectedConditionRegistry.FolderKey).ToHashSet();
|
||
if (!condition.Placements.SequenceEqual(placements)) condition.PlacementVersion++;
|
||
condition.Placements = placements;
|
||
foreach (var key in before.Except(after))
|
||
if (_importedConditions.ByFolderKey.TryGetValue(key, out var set) && set.Remove(condition.Alarm.NodeId) && set.Count == 0)
|
||
_importedConditions.ByFolderKey.Remove(key);
|
||
foreach (var key in after)
|
||
{
|
||
if (!_importedConditions.ByFolderKey.TryGetValue(key, out var set)) _importedConditions.ByFolderKey[key] = set = [];
|
||
set.Add(condition.Alarm.NodeId);
|
||
}
|
||
var desired = new HashSet<FolderState>(ReferenceEqualityComparer.Instance);
|
||
foreach (var key in after) if (FindProjectedFolder(key) is { } f) desired.Add(f);
|
||
foreach (var folder in condition.Folders.Where(f => !desired.Contains(f)).ToList()) UnwireImportedFolder(condition, folder);
|
||
foreach (var folder in desired) WireImportedFolder(condition, folder);
|
||
}
|
||
|
||
private void WireImportedFolder(ImportedCondition condition, FolderState folder)
|
||
{
|
||
if (condition.Folders.Contains(folder)) return;
|
||
if (_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var entry) && !ReferenceEquals(entry.Folder, folder))
|
||
{
|
||
// S1 backstop: a dead instance with this NodeId is still recorded — unwire it, then promote the new one.
|
||
foreach (var id in entry.Conditions.ToList())
|
||
if (_importedConditions.Find(id) is { } stale) UnwireImportedFolder(stale, entry.Folder);
|
||
_importedConditions.WiredByFolder.Remove(folder.NodeId);
|
||
}
|
||
condition.Folders.Add(folder);
|
||
condition.WiredFolders = [.. condition.Folders];
|
||
condition.Alarm.AddNotifier(SystemContext, NodeId.Null, isInverse: true, folder);
|
||
folder.AddNotifier(SystemContext, NodeId.Null, isInverse: false, condition.Alarm);
|
||
if (!_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out entry))
|
||
{
|
||
_importedConditions.WiredByFolder[folder.NodeId] = entry = (folder, []);
|
||
// Projected folders are created with EventNotifier = None (NM projected page sink); promoted only while wired.
|
||
folder.EventNotifier = (byte)(folder.EventNotifier | EventNotifiers.SubscribeToEvents);
|
||
AddRootNotifier(folder);
|
||
folder.ClearChangeMasks(SystemContext, includeChildren: false);
|
||
}
|
||
entry.Conditions.Add(condition.Alarm.NodeId);
|
||
condition.PlacementVersion++;
|
||
}
|
||
|
||
private void UnwireImportedFolder(ImportedCondition condition, FolderState folder)
|
||
{
|
||
if (!condition.Folders.Remove(folder)) return;
|
||
condition.WiredFolders = [.. condition.Folders];
|
||
condition.Alarm.RemoveNotifier(SystemContext, folder, bidirectional: true);
|
||
condition.PlacementVersion++;
|
||
if (_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var entry) && ReferenceEquals(entry.Folder, folder)
|
||
&& entry.Conditions.Remove(condition.Alarm.NodeId) && entry.Conditions.Count == 0)
|
||
{
|
||
_importedConditions.WiredByFolder.Remove(folder.NodeId);
|
||
RemoveRootNotifier(folder);
|
||
if (!_importedConditions.PromotedFolders.Contains(folder.NodeId))
|
||
folder.EventNotifier = (byte)(folder.EventNotifier & ~EventNotifiers.SubscribeToEvents);
|
||
folder.ClearChangeMasks(SystemContext, includeChildren: false);
|
||
}
|
||
}
|
||
|
||
/// <summary>A projected folder (or anchor) materialised: index it and wire every imported condition placed there (N7). Under Lock.</summary>
|
||
private void OnProjectedFolderMaterialised(FolderState folder, string mappingId, string localSubject)
|
||
{
|
||
if (_importedConditions.FolderKeys.Remove(folder.NodeId, out var previous)) _importedConditions.FolderIds.Remove(previous);
|
||
_importedConditions.FolderIds[(mappingId, localSubject)] = folder.NodeId;
|
||
_importedConditions.FolderKeys[folder.NodeId] = (mappingId, localSubject);
|
||
if (ProjectedConditionAccess is { } access && access.IsConditionBearingMapping(mappingId))
|
||
{
|
||
// Deviation 3 (review r1): a folder-only client can subscribe (and so open condition demand) before anything is wired.
|
||
_importedConditions.PromotedFolders.Add(folder.NodeId);
|
||
folder.EventNotifier = (byte)(folder.EventNotifier | EventNotifiers.SubscribeToEvents);
|
||
}
|
||
if (_importedConditions.Count == 0 || !_importedConditions.ByFolderKey.TryGetValue((mappingId, localSubject), out var set)) return;
|
||
foreach (var id in set.ToList())
|
||
if (_importedConditions.Find(id) is { } c) WireImportedFolder(c, folder);
|
||
}
|
||
|
||
/// <summary>
|
||
/// A4 F4: promotes, just before the SDK attaches an ADMITTED event item to it (and refuses a node without
|
||
/// <c>SubscribeToEvents</c>, <c>BadNotSupported</c>), a materialised projected folder whose mapping was not yet
|
||
/// condition-bearing when it materialised — its authority activates at the consumer's first barrier, after the projected
|
||
/// pages were served. Nothing re-promoted it, so a folder-first client on a freshly restarted consumer was refused until an
|
||
/// <c>i=2253</c> item opened demand and a condition got wired there. One dictionary probe; caller holds no lock.
|
||
/// </summary>
|
||
/// <param name="folderId">The projected notifier the item targets.</param>
|
||
private void PromoteProjectedEventFolder(NodeId folderId)
|
||
{
|
||
if (ProjectedConditionAccess is not { } access) return;
|
||
lock (Lock)
|
||
{
|
||
if (_importedConditions.PromotedFolders.Contains(folderId) || !_importedConditions.FolderKeys.TryGetValue(folderId, out var key)) return;
|
||
if (!access.IsConditionBearingMapping(key.Mapping) || FindProjectedFolder(key) is not { } folder) return;
|
||
_importedConditions.PromotedFolders.Add(folder.NodeId);
|
||
folder.EventNotifier = (byte)(folder.EventNotifier | EventNotifiers.SubscribeToEvents);
|
||
folder.ClearChangeMasks(SystemContext, includeChildren: false);
|
||
}
|
||
}
|
||
|
||
/// <summary>A projected folder is being removed: unwire it symmetrically first (N7) and drop it from the index. Under Lock.</summary>
|
||
private void OnProjectedFolderRemoving(NodeId folderId)
|
||
{
|
||
if (_importedConditions.FolderKeys.Remove(folderId, out var key)) _importedConditions.FolderIds.Remove(key);
|
||
_importedConditions.PromotedFolders.Remove(folderId);
|
||
if (!_importedConditions.WiredByFolder.TryGetValue(folderId, out var entry)) return;
|
||
foreach (var id in entry.Conditions.ToList())
|
||
if (_importedConditions.Find(id) is { } c) UnwireImportedFolder(c, entry.Folder);
|
||
}
|
||
|
||
/// <summary>Review r1 S1: a full rebuild discards every projected folder — unwire all of them (and clear the index) before
|
||
/// the maps are cleared, so a re-materialised folder is promoted and wired afresh. Under Lock.</summary>
|
||
private void UnwireAllImportedFolders()
|
||
{
|
||
foreach (var folderId in _importedConditions.WiredByFolder.Keys.ToList()) OnProjectedFolderRemoving(folderId);
|
||
_importedConditions.FolderIds.Clear();
|
||
_importedConditions.FolderKeys.Clear();
|
||
_importedConditions.PromotedFolders.Clear();
|
||
}
|
||
|
||
/// <summary>
|
||
/// N7: a projected folder holding an admitted event item is pinned — capacity eviction and page removal skip it (a
|
||
/// mapping removal still removes it, unwiring first). Under Lock.
|
||
/// </summary>
|
||
private bool IsPinnedEventFolder(NodeId nodeId) =>
|
||
(_importedConditions.WiredByFolder.ContainsKey(nodeId) || _importedConditions.FolderKeys.ContainsKey(nodeId))
|
||
&& MonitoredNodes.TryGetValue(nodeId, out var monitored) && monitored.EventMonitoredItems is { Count: > 0 };
|
||
|
||
/// <summary>
|
||
/// A projected folder (or anchor) event items are admitted on through the verified path (§5.4): one wired as a notifier of
|
||
/// an imported condition, or — deviation 3, review r1 — any materialised projected folder, so a folder-only client can
|
||
/// open condition demand before any condition is wired there.
|
||
/// </summary>
|
||
private bool IsProjectedEventNotifier(NodeId nodeId)
|
||
{
|
||
if (ProjectedConditionAccess is null) return false;
|
||
lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(nodeId) || _importedConditions.FolderKeys.ContainsKey(nodeId);
|
||
}
|
||
|
||
/// <summary>
|
||
/// §5.4 admission (and revalidation, review r1 B3) of an event item on a projected notifier: the caller sees at least one
|
||
/// condition wired there, or passes the mapping gate on the folder's own (mapping, local subject) placement key.
|
||
/// </summary>
|
||
private bool ImportedNotifierAdmits(RoleCarryingUserIdentity? identity, NodeId notifierId)
|
||
{
|
||
List<ImportedCondition> wired = [];
|
||
(string Mapping, string Subject)? key = null;
|
||
lock (Lock)
|
||
{
|
||
if (_importedConditions.WiredByFolder.TryGetValue(notifierId, out var entry))
|
||
wired = entry.Conditions.Select(_importedConditions.Find).OfType<ImportedCondition>().ToList();
|
||
if (_importedConditions.FolderKeys.TryGetValue(notifierId, out var folderKey)) key = folderKey;
|
||
}
|
||
if (wired.Any(c => ImportedVisibleTo(identity, c))) return true;
|
||
return key is { } k && identity is not null && ProjectedConditionAccess is { } access && access.CanSubscribeFolder(identity, k.Mapping, k.Subject);
|
||
}
|
||
|
||
/// <summary>
|
||
/// The authorizer's pre-realm classifier (§5.2): null for any id outside the imported-condition namespace, otherwise
|
||
/// the imported verdict.
|
||
/// </summary>
|
||
internal bool? ClassifyImportedCondition(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId) =>
|
||
IsImportedConditionId(nodeId) ? AuthorizeImportedCondition(identity, operation, nodeId) : null;
|
||
|
||
/// <summary>Test observation: whether a projected folder is currently wired as a notifier of some imported condition.</summary>
|
||
/// <summary>Test observation (A4 review r2): a projected folder's <c>EventNotifier</c> (null when it is no known projected folder).</summary>
|
||
internal byte? ProjectedFolderEventNotifier(NodeId folderId)
|
||
{
|
||
lock (Lock)
|
||
return _importedConditions.FolderKeys.TryGetValue(folderId, out var key) && FindProjectedFolder(key) is { } folder
|
||
? folder.EventNotifier : null;
|
||
}
|
||
|
||
internal bool IsImportedNotifierWired(NodeId folderId)
|
||
{
|
||
lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(folderId);
|
||
}
|
||
|
||
/// <summary>Test observation: the imported condition node for (connection, key), or null.</summary>
|
||
internal AlarmConditionState? FindImportedCondition(string connectionId, string conditionKey) =>
|
||
_importedConditions.Find(ImportedConditionNodeId(connectionId, conditionKey))?.Alarm;
|
||
|
||
// ---------------------------------------------------------------------------------------------------------------------
|
||
// Demand + ConditionRefresh
|
||
// ---------------------------------------------------------------------------------------------------------------------
|
||
|
||
/// <summary>An admitted event item (Server object or projected notifier) opens condition demand; its removal releases it.</summary>
|
||
private void TrackImportedDemand(IEventMonitoredItem item, bool unsubscribe)
|
||
{
|
||
if (unsubscribe)
|
||
{
|
||
if (_importedEventDemand.TryRemove(item, out var lease)) lease.Dispose();
|
||
return;
|
||
}
|
||
if (ProjectedConditionAccess is not { } access || _importedEventDemand.ContainsKey(item)) return;
|
||
IDisposable? acquired;
|
||
try { acquired = access.AcquireEventDemand(item.EffectiveIdentity as RoleCarryingUserIdentity); }
|
||
catch (Exception ex) { _logger.LogWarning(ex, "OtOpcUaNodeManager: imported condition demand failed"); return; }
|
||
if (acquired is not null && !_importedEventDemand.TryAdd(item, acquired)) acquired.Dispose();
|
||
}
|
||
|
||
/// <summary>
|
||
/// ConditionRefresh for imported conditions: every retained one the item may see, through the marked path. Server-object
|
||
/// items see all; a direct item only those wired to its notifier. Review r1 (deviation 8): chunked at
|
||
/// <see cref="ImportedApplyChunk"/> conditions per <c>Lock</c> hold; each condition's snapshot and its queueing happen in the
|
||
/// same hold (so its ordering against its live events holds), and one <see cref="EventDeliveryCache"/> per condition
|
||
/// snapshot is shared by every item it is queued to (one projection, not one per item).
|
||
/// </summary>
|
||
private void ReplayImportedConditions(List<IEventMonitoredItem> serverItems, List<IEventMonitoredItem> directItems)
|
||
{
|
||
if (_importedConditions.Count == 0) return;
|
||
var all = _importedConditions.All.ToList();
|
||
for (var start = 0; start < all.Count; start += ImportedApplyChunk)
|
||
{
|
||
lock (Lock)
|
||
{
|
||
var direct = directItems.Where(item => MonitoredItems.ContainsKey(item.Id))
|
||
.Select(item => (Item: item, Notifier: (item.ManagerHandle as NodeHandle)?.Node as FolderState))
|
||
.Where(x => x.Notifier is not null).ToList();
|
||
for (var i = start; i < Math.Min(all.Count, start + ImportedApplyChunk); i++)
|
||
{
|
||
var c = all[i];
|
||
if (!_importedConditions.IsLive(c.Alarm) || c.Alarm.Retain?.Value != true) continue;
|
||
InstanceStateSnapshot? snapshot = null;
|
||
EventDeliveryCache? cache = null;
|
||
void Queue(IEventMonitoredItem item)
|
||
{
|
||
if (!ImportedVisibleTo(item, c) || ServiceResult.IsBad(ValidateEventRolePermissions(item, c.Alarm))) return;
|
||
if (snapshot is null)
|
||
{
|
||
snapshot = new InstanceStateSnapshot();
|
||
snapshot.Initialize(SystemContext, c.Alarm);
|
||
cache = new EventDeliveryCache();
|
||
}
|
||
cache!.QueueMarked(Server, item, snapshot, x => ImportedMarker(x, c));
|
||
}
|
||
foreach (var item in serverItems) Queue(item);
|
||
foreach (var (item, notifier) in direct)
|
||
if (c.Folders.Contains(notifier!)) Queue(item);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|