using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; using ZB.MOM.WW.OtOpcUa.Commons.Observability; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.OpcUaServer; using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// A3: the deployed mapping placements the condition runtime reads (an adapter over ). public interface IProjectedConditionMappings { /// The currently published placements (copies; read on change only). IReadOnlyList Current { get; } /// Raised after the published placement set changes. event Action? Changed; /// /// A4 F1–F3: a catalog attempt (a deploy) is in progress. Its is an empty set that says "not /// decided yet", not "every mapping removed" — the conditions of a connection that drops out now are HELD, and /// removed only if the settled set no longer has that connection. /// bool Suspended => false; /// /// A4 review r2 S1: and as ONE consistent pair. A reader that pairs a live /// "settled" flag with a placement list copied earlier (still the deploy's empty set) would release held conditions. /// (IReadOnlyList Current, bool Suspended) Snapshot => (Current, Suspended); } /// The production adapter over . /// /// A4 review r2 S1: the placements and the "attempt undecided" flag arrive TOGETHER in one /// captured under the runtime's transition lock, and are kept as one volatile reference — /// never the runtime's live flag next to a list copied by an earlier notification. Sets delivered out of order (two /// transitions notifying concurrently) are ordered by ; an older one is ignored. /// public sealed class DeployedConditionMappings : IProjectedConditionMappings { private ProjectedMappingSet _set = null!; public DeployedConditionMappings(ProjectedMappingDeploymentRuntime runtime) { ArgumentNullException.ThrowIfNull(runtime); runtime.SetChanged += OnSetChanged; // After subscribing: a transition racing the constructor is either in this read or delivered to the handler. Publish(runtime.Set); } private void OnSetChanged(ProjectedMappingSet set) { if (Publish(set)) Changed?.Invoke(); } private bool Publish(ProjectedMappingSet set) { while (true) { var seen = Volatile.Read(ref _set); if (seen is not null && seen.Sequence >= set.Sequence) return false; if (ReferenceEquals(Interlocked.CompareExchange(ref _set, set, seen), seen)) return true; } } public IReadOnlyList Current => Volatile.Read(ref _set).Placements; public event Action? Changed; /// public bool Suspended => Volatile.Read(ref _set).Suspended; /// public (IReadOnlyList Current, bool Suspended) Snapshot { get { var set = Volatile.Read(ref _set); return (set.Placements, set.Suspended); } } } /// A3 host limits (§5.5 "Budget"). /// How long a connection's condition items stay open after the last event item goes (default 30 s). /// Per consumer node (default 122,500 = 2,500 × 49). /// Per consumer node (default = L2-measured × 2,500 ≈ 381 MiB). /// Pause before re-opening an ended condition stream. public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedConditionNodes, long MaxImportedConditionBytes, TimeSpan ReconnectDelay) { /// Counted, not estimated (plan §5.5 table): the worst case per condition. public const int NodesPerCondition = 49; /// /// Retained managed bytes per imported condition, measured by the A3 L2 harness (1,000 conditions in one mapping on a /// running SDK 2.0.1 server: node + children + ids + registry/indexes + EventId registry + verdict cache; X0's /// node-only harness retains 79,085 B on the same method, #929 — its original 160,997 was a GC.GetTotalMemory delta). A3b review S5: the WORST case — two placements, every EventId slot, three /// event items, the runner's Live + Buffer records. A3 review round 2: measured with the retained heap /// (GCMemoryInfo, not GC.GetTotalMemory, which counted ~125 MiB of committed-but-free regions) and the /// settled working set, 8 EventId slots (§5.6): max of three runs = 158,629 B (working set; heap 111,715 B), rounded up. /// public const long BytesPerCondition = 160_000; /// §9.3 L2: the host byte cap = measured per-condition bytes × 2,500 (the host condition cap). public const long DefaultMaxImportedConditionBytes = BytesPerCondition * 2_500; /// /// #930 (N2/N3): the base in-stream retry delay of a mapping the origin refused DEFINITIVELY (Denied, /// NotFound, Unsupported, for its item or its root metadata) or that is over capacity /// (); doubled per consecutive retry up to 4×. A transient /// refusal or a snapshot timeout retries after ConditionSnapshotTimeoutMilliseconds × 2ⁿ (≤ 8×). Either way the /// mapping's item is re-added on the OPEN stream — the healthy mappings are never re-snapshotted for it. /// public TimeSpan LongRetryDelay { get; init; } = TimeSpan.FromMinutes(5); /// #931 (N4): the ceiling of the exponential reconnect backoff after streams that end before their barrier. public TimeSpan MaxReconnectDelay { get; init; } = TimeSpan.FromSeconds(60); /// /// A4 review r2 S2: the longest a connection's conditions are HELD for an undecided deploy (a catalog attempt that /// began and has not completed). Past it they are released (removed) as if the attempt had settled without the /// connection. Any completion settles sooner; this bounds an attempt that never completes. The default is 2.5× the /// deploy apply deadline (DeployTimings.ApplyDeadline, 120 s): an attempt still open by then is not finishing. /// Before it, the held conditions go BadNoCommunication on the connection's stale timeout, as for any stream gap. /// public TimeSpan MaxHold { get; init; } = TimeSpan.FromMinutes(5); /// /// #933: the longest a materialised condition that no KNOWN mapping lists is kept (BadNoCommunication) because /// another mapping of the connection is unknown (Unavailable, Denied, retrying). Past it the condition is removed — a /// removal with RefreshRequired, never "known inactive" (§5.1 T2) — and re-created if the unknown mapping lists it again. /// Scoping the hold to "mappings that could list the key" is not provable on the consumer: a mapping lists a key when the /// origin's CURRENT catalog places the condition under that mapping's root, and placements are origin deploy-time /// configuration (a dropped key may have moved into the unknown mapping's scope). The default (20 min) is ~4× the longest /// transient retry cycle at the default 30 s snapshot timeout (× 8 = 4 min, + the retry's own timeout) and spans the first /// two in-stream re-checks of a definitive refusal ( 5 min, then 10 min), so a transient /// outage or a corrected grant never removes anything; only a durable one does. /// public TimeSpan MaxUnknownHold { get; init; } = TimeSpan.FromMinutes(20); public static ProjectedConditionOptions Default { get; } = new(TimeSpan.FromSeconds(30), 122_500, DefaultMaxImportedConditionBytes, TimeSpan.FromSeconds(1)); } /// Why a condition-bearing mapping is not contributing conditions. public enum ProjectedConditionMappingStatus { Pending, Snapshotting, Complete, Unavailable, ConditionCapacity } /// /// A3 (plan §5.4, §5.5): the consumer's condition runtime. /// /// Gate (): the mapping gate for CreateMonitoredItems on ANY current placement /// mapping — the mapping's Subscribe + AlarmSubscribe bits and a local Subscribe grant on the placement folder's local /// scope — regardless of Security:Acl:Enabled. /// Demand: the first admitted event item opens, per condition-bearing connection, ONE stream with one /// root-scoped condition item per enabled condition-bearing mapping (under the connection's service principal); /// they close together after the last item goes plus . /// Barrier + budget: total > MaxConditions ⇒ that mapping is /// and its item removed before anything is /// materialised; host caps reject the mappings that would cross them, in deployed order; conditions are materialised /// only after every mapping completed its snapshot (or timed out ⇒ Unavailable). /// Versions: per key and epoch; a removed record and a snapshot begin bypass the gate; a removal is /// applied unconditionally and forgets the key's version. /// Lifetime: a stream end is "re-snapshot", never "conditions removed"; only a COMPLETE re-snapshot that /// no longer lists a key removes it. Past ConditionStaleTimeoutMilliseconds without a stream the conditions go /// BadNoCommunication (one event each) — never "known inactive" (§5.1 T2). /// /// public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess, IDisposable { private readonly IProjectedConditionMappings _mappings; private readonly IGrpcDataAdapterConnectionSource _connections; private readonly DataOperationPolicy _policy; private readonly Func _sink; private readonly TimeProvider _clock; private readonly ProjectedConditionOptions _options; private readonly ILogger _log; private readonly object _gate = new(); /// Mutated under only; concurrent so a method call reads its runner's Serving without /// taking (#931 N6: _gate can sit behind a stop that waits on _staleGate). private readonly ConcurrentDictionary _runners = new(StringComparer.OrdinalIgnoreCase); /// Review r1 S3/S4: a stopped runner's completion (its loop AND its removal) per connection; the next runner of /// that connection awaits it before opening a stream or taking the materialised set, so the two never overlap. private readonly Dictionary _stopping = new(StringComparer.OrdinalIgnoreCase); /// /// A4 F1–F3: runners stopped WITHOUT removal because their connection dropped out of a suspended (deploying) mapping /// set. The connection's next runner takes their materialised set over (same conditions, same EventIds, no re-create); /// a settled set without the connection releases them (removal). Under . /// /// A4 review r2 S2: concurrent (mutated under only) so a diagnostics poll reports a held /// connection as held without taking _gate. private readonly ConcurrentDictionary _held = new(StringComparer.OrdinalIgnoreCase); private readonly ConditionLedger _ledger; private int _demand; private long _mappingVersion = 1; private ITimer? _linger; private bool _disposed; public ProjectedConditionAccess(IProjectedConditionMappings mappings, IGrpcDataAdapterConnectionSource connections, DataOperationPolicy policy, Func? sink, TimeProvider clock, ProjectedConditionOptions? options = null, ILogger? logger = null, DataConnectionConditionDiagnostics? diagnostics = null) { _mappings = mappings ?? throw new ArgumentNullException(nameof(mappings)); Diagnostics = diagnostics ?? new DataConnectionConditionDiagnostics(); _connections = connections ?? throw new ArgumentNullException(nameof(connections)); _policy = policy ?? throw new ArgumentNullException(nameof(policy)); _sink = sink ?? (() => Sink); _clock = clock ?? throw new ArgumentNullException(nameof(clock)); _options = options ?? ProjectedConditionOptions.Default; // #933 review r1 N3: zero or negative would remove every held key at once — the bound must be a real duration. if (_options.MaxUnknownHold <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(options), _options.MaxUnknownHold, "MaxUnknownHold must be positive."); _log = logger ?? NullLogger.Instance; _ledger = new ConditionLedger(_options); _mappings.Changed += OnMappingsChanged; Diagnostics.AttachConsumer(CaptureConsumer); } /// A4: the diagnostics/metrics this runtime reports into (shared with the diagnostics readers). public DataConnectionConditionDiagnostics Diagnostics { get; } /// A4: one connection's consumer condition state; null when no current mapping of it is condition-bearing. private DataConnectionConditionDiagnostics.ConsumerState? CaptureConsumer(string connectionId) { var mappings = _mappings.Current.Where(x => string.Equals(x.Mapping.DataConnectionId, connectionId, StringComparison.OrdinalIgnoreCase) && x.Authority.IsActive && IsConditionBearing(x.Mapping)).ToArray(); // A4 review r2 S2: a connection held for an undecided deploy has no current mapping, but its conditions exist and are // charged — report them as "held" instead of hiding them. if (!_runners.ContainsKey(connectionId) && _held.TryGetValue(connectionId, out var held)) { var (_, heldAt, heldCount, heldUnknown, _) = held.Capture(); return new("held", heldAt, heldCount, heldUnknown, [], _ledger.Total, _ledger.ConditionLimit); } if (mappings.Length == 0) return null; // #931 N6 spirit: a diagnostics poll never takes _gate either. if (!_runners.TryGetValue(connectionId, out var runner)) return new("idle", null, 0, 0, OrderMappings(mappings).Select(x => new ConditionMappingDiagnostics(x.Mapping.RemoteNamespaceMappingId, ProjectedConditionMappingStatus.Pending.ToString(), 0, x.Mapping.MaxConditions)).ToArray(), _ledger.Total, _ledger.ConditionLimit); var (state, snapshotAt, materialised, unknown, rows) = runner.Capture(); return new(state, snapshotAt, materialised, unknown, rows, _ledger.Total, _ledger.ConditionLimit); } /// The node manager the host binds once the server is up (used when no sink delegate was supplied). public IProjectedConditionSink? Sink { get; set; } /// Whether a mapping is condition-bearing: enabled, Subscribe + AlarmSubscribe granted. public static bool IsConditionBearing(RemoteNamespaceMapping mapping) => mapping.Enabled && (mapping.AllowedOperations & (DataOperations.Subscribe | DataOperations.AlarmSubscribe)) == (DataOperations.Subscribe | DataOperations.AlarmSubscribe); /// /// Review r1 S2: also folds each current mapping's Authority.IsActive, which flips without a deploy. public long AuthorityGeneration { get { var active = 17L; foreach (var mapping in _mappings.Current) active = unchecked(active * 31 + (mapping.Authority.IsActive ? 1 : 2)); return unchecked((Interlocked.Read(ref _mappingVersion) << 32) ^ _policy.AuthorityEpoch ^ (active << 1)); } } /// public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList placements) { if (caller is null || string.IsNullOrWhiteSpace(caller.Principal) || placements.Count == 0) return false; var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc); var current = _mappings.Current; foreach (var placement in placements) if (Gate(identity, current, placement.MappingId, placement.Realm, placement.FolderLocalSubject)) return true; return false; } /// public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) { if (caller is null || string.IsNullOrWhiteSpace(caller.Principal)) return false; var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc); return Gate(identity, _mappings.Current, mappingId, null, folderLocalSubject); } /// public bool IsConditionBearingMapping(string mappingId) => _mappings.Current.Any(x => string.Equals(x.Mapping.RemoteNamespaceMappingId, mappingId, StringComparison.OrdinalIgnoreCase) && x.Authority.IsActive && IsConditionBearing(x.Mapping)); /// The mapping gate for one (mapping, folder) placement; null = the mapping's own. private bool Gate(DataCallerIdentity identity, IReadOnlyList current, string mappingId, DataRealm? realm, string folderLocalSubject) { var mapping = current.FirstOrDefault(x => string.Equals(x.Mapping.RemoteNamespaceMappingId, mappingId, StringComparison.OrdinalIgnoreCase)); if (mapping is null || !mapping.Authority.IsActive || !IsConditionBearing(mapping.Mapping) || (realm is { } r && mapping.Mapping.Realm != r)) return false; if (!TryFolderScope(mapping, folderLocalSubject, out var scope)) return false; try { return _policy.AuthorizeLocal(identity, OpcUaOperation.CreateMonitoredItems, scope); } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; } } /// The local scope of a placement's folder: the mapping's local scope plus the folder's path below the anchor. internal static bool TryFolderScope(ProjectedMappingPlacement mapping, string folderLocalSubject, out NodeScope scope) { scope = mapping.Scope; var anchor = string.Join('/', mapping.Scope.Segments); if (string.Equals(folderLocalSubject, anchor, StringComparison.Ordinal)) return true; if (!folderLocalSubject.StartsWith(anchor + "/", StringComparison.Ordinal)) return false; var below = folderLocalSubject[(anchor.Length + 1)..].Split('/'); if (below.Any(string.IsNullOrEmpty)) return false; scope = mapping.Scope with { Segments = Array.AsReadOnly(mapping.Scope.Segments.Concat(below).ToArray()) }; return true; } /// public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller) { lock (_gate) { if (_disposed) return null; _demand++; _linger?.Dispose(); _linger = null; ReconcileRunners(); } return new DemandLease(this); } private void ReleaseDemand() { lock (_gate) { if (_disposed || --_demand > 0) return; _linger?.Dispose(); _linger = _clock.CreateTimer(_ => OnLingerExpired(), null, _options.Linger, Timeout.InfiniteTimeSpan); } } private void OnLingerExpired() { List stopped; lock (_gate) { if (_disposed || _demand > 0) return; stopped = _runners.Values.ToList(); _runners.Clear(); foreach (var runner in stopped) { runner.Stop(removeConditions: true); Park(runner); } ReleaseHeld(_ => true); } } /// A4 review r2 S2: the hold bound — a still-held runner (the same one) is released once passes. private void OnHoldExpired(string connectionId, ConnectionRunner runner) { lock (_gate) { if (_disposed || !_held.TryGetValue(connectionId, out var held) || !ReferenceEquals(held, runner)) return; _log.LogWarning("Imported conditions: connection {Connection} held for an undecided deploy longer than {MaxHold}; releasing its conditions", connectionId, _options.MaxHold); ReleaseHeld(id => string.Equals(id, connectionId, StringComparison.OrdinalIgnoreCase)); } } /// A4 F1–F3, under _gate: releases (removes the conditions of) the held runners selects. private void ReleaseHeld(Func release) { foreach (var id in _held.Keys.Where(release).ToList()) { _held.TryRemove(id, out var held); held!.ReleaseHeld(); Park(held); } } private void OnMappingsChanged() { Interlocked.Increment(ref _mappingVersion); lock (_gate) { if (_disposed) return; ReconcileRunners(); // A4 review r2 S2: a held connection keeps its counters (it is still reported, as "held"). var retained = _mappings.Current.Select(x => x.Mapping.DataConnectionId).ToHashSet(StringComparer.OrdinalIgnoreCase); retained.UnionWith(_held.Keys); Diagnostics.RetainConsumers(retained); } } /// Starts a runner per condition-bearing connection while demand exists; restarts one whose mapping set changed. Under _gate. private void ReconcileRunners() { // A4 review r2 S1: ONE consistent (placements, suspended) pair — a live flag next to an older list would release. var (current, suspended) = _mappings.Snapshot; var byConnection = current.Where(x => x.Authority.IsActive && IsConditionBearing(x.Mapping)) .GroupBy(x => x.Mapping.DataConnectionId, StringComparer.OrdinalIgnoreCase) .ToDictionary(x => x.Key, x => OrderMappings(x).ToArray(), StringComparer.OrdinalIgnoreCase); // A4 F1–F3: only a SETTLED set that no longer has the connection removes its held conditions. if (!suspended) ReleaseHeld(id => !byConnection.ContainsKey(id) || _demand <= 0); if (_demand <= 0) return; foreach (var id in _runners.Keys.Where(id => !byConnection.ContainsKey(id)).ToList()) { _runners.TryRemove(id, out var gone); if (suspended) { // A4 F1–F3: every deploy begins with an empty, undecided set. Removing here tore down every imported condition // and re-created it after the deploy (a fresh node ⇒ a phantom event per condition, new EventIds, the old ones // BadEventIdUnknown, and the removal's RefreshRequired gated away because nothing was visible any more). Hold: // the next runner of this connection takes the conditions over and re-snapshots onto them. gone!.Stop(removeConditions: false); // A4 review r2 S2: bounded — stale on the connection's stale timeout, released past MaxHold. gone.Hold(_clock.CreateTimer(_ => OnHoldExpired(id, gone), null, _options.MaxHold, Timeout.InfiniteTimeSpan)); _held[id] = gone; continue; } gone!.Stop(removeConditions: true); Park(gone); } foreach (var (id, mappings) in byConnection) { var signature = Signature(mappings); if (_runners.TryGetValue(id, out var running)) { if (running.Signature == signature) continue; // A changed mapping set: a new stream with a complete snapshot. ConditionIds never change (N4); placements, // notifiers and SourceName follow the new set at its barrier. running.Stop(removeConditions: false); } // S3/S4: the predecessor (still running or still removing) hands over only after it has fully stopped. ConnectionRunner? held = null; if (running is null && _held.TryRemove(id, out held)) held.EndHold(); // under _gate: no stale mark lands after this var predecessor = running ?? held ?? (_stopping.Remove(id, out var stopping) ? stopping : null); // A4 review r2 S3: a runner that takes a HELD set over tells clients to refresh once at its first barrier. var runner = new ConnectionRunner(this, id, mappings, signature, predecessor, tookOverHeld: held is not null); _runners[id] = runner; runner.Start(); } } /// /// Under _gate: parks a removing runner so the connection's next runner awaits its removal (S3/S4). #931 N8: the entry /// is dropped once that removal has finished — a removing stop hands over an empty set, so nothing is left to wait for, /// and a connection that never returns no longer pins its last runner. /// private void Park(ConnectionRunner runner) { _stopping[runner.ConnectionId] = runner; runner.Stopped.ContinueWith(_ => { lock (_gate) if (_stopping.TryGetValue(runner.ConnectionId, out var parked) && ReferenceEquals(parked, runner)) _stopping.Remove(runner.ConnectionId); }, TaskScheduler.Default); } /// Test observation (#931 N8): whether a stopped runner of the connection is still parked. public bool IsParked(string connectionId) { lock (_gate) return _stopping.ContainsKey(connectionId); } /// §5.2: Raw mappings before UNS, then mapping id ordinal (deployed configuration only). internal static IEnumerable OrderMappings(IEnumerable mappings) => mappings.OrderBy(x => x.Mapping.Realm == DataRealm.Raw ? 0 : 1) .ThenBy(x => x.Mapping.RemoteNamespaceMappingId, StringComparer.Ordinal); private static string Signature(IEnumerable mappings) => string.Join('|', mappings.Select(x => $"{x.Mapping.RemoteNamespaceMappingId}:{x.Mapping.Revision}:{x.Mapping.MaxConditions}:{x.Anchor.Subject}")); /// Test/diagnostic observation: a connection's mapping statuses (null when no runner). public IReadOnlyDictionary? MappingStatuses(string connectionId) { lock (_gate) return _runners.TryGetValue(connectionId, out var runner) ? runner.Statuses : null; } /// Test/diagnostic observation: imported conditions charged against the node-wide host caps (review r1 B4). public long ChargedConditions => _ledger.Total; /// Test observation: whether a connection has an open runner. public bool IsRunning(string connectionId) { lock (_gate) return _runners.ContainsKey(connectionId); } /// Test observation (verification r2 N1): a weak reference to the connection's current (or still stopping) runner. public WeakReference? RunnerReference(string connectionId) { lock (_gate) return _runners.TryGetValue(connectionId, out var runner) || _stopping.TryGetValue(connectionId, out runner) ? new WeakReference(runner) : null; } /// Test observation: snapshot barriers a connection completed. public int BarriersCompleted(string connectionId) { lock (_gate) return _runners.TryGetValue(connectionId, out var runner) ? runner.Barriers : 0; } public void Dispose() { List runners; lock (_gate) { if (_disposed) return; _disposed = true; _linger?.Dispose(); runners = _runners.Values.ToList(); _runners.Clear(); // Review r2 NIT: the held runners are already stopped; end their hold timers and drop them. foreach (var held in _held.Values) held.EndHold(); _held.Clear(); } _mappings.Changed -= OnMappingsChanged; foreach (var runner in runners) runner.Stop(removeConditions: false); } private sealed class DemandLease(ProjectedConditionAccess owner) : IDisposable { private int _disposed; public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) owner.ReleaseDemand(); } } }