using Akka.Actor; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; internal interface IObsoleteProjectedSample { bool CanDropExpiredPredecessor { get; } } internal static class ProjectedEvidenceRetirement { internal static bool CanDrop(IProjectedSamplePublicationProof proof) { try { return !proof.IsValid && proof.IsSourceValid && proof is IObsoleteProjectedSample { CanDropExpiredPredecessor: true }; } catch (Exception) { return false; } } } /// Owns bounded imported-value messages through the actual SDK apply, with captured route ownership. public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDisposable { private sealed class Binding(ProjectedValueRoute route) { internal ProjectedValueRoute Route { get; } = route; internal object? SourceIdentity; internal object? PublicationIdentity; } private readonly object _sync = new(); private readonly Dictionary<(DataRealm, string), Binding> _bindings = new(); private readonly HashSet _pending = []; private readonly HashSet _retiredReferences = new(StringComparer.Ordinal); private readonly Dictionary _trackedReferences = new(StringComparer.Ordinal); private long _controlBytes; private readonly long _maximumControlBytes; private IActorRef? _retirementHost; private bool _retirementWakePending; private IActorRef? _valueHost; private bool _valueWakePending; private IActorRef? _sdkActor; private bool _sdkWakePending; private readonly HashSet _sdkPending = []; private IActorRef? _muxTarget; private ProjectedCoalescingMailbox? _muxMailbox; private readonly Func _host; private readonly Func _authority; private readonly int _maximumRoutes; private readonly long _maximumBytes; private readonly TimeProvider _clock; private readonly ITimer _cleanup; private long _pendingBytes; private long _nextQueueSequence; private bool _disposed; public ActorProjectedValuePublisher(Func host, Func authority, int maximumRoutes, long maximumPendingBytes, TimeProvider clock, long maximumControlBytes = 16 * 1024 * 1024) { if (maximumRoutes <= 0 || maximumPendingBytes <= 0 || maximumControlBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maximumRoutes)); _host = host; _authority = authority; _maximumRoutes = maximumRoutes; _maximumBytes = maximumPendingBytes; _clock = clock; _maximumControlBytes = maximumControlBytes; _cleanup = clock.CreateTimer(static state => ((ActorProjectedValuePublisher)state!).SweepQueued(), this, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)); } public long PendingBytes { get { lock (_sync) return _pendingBytes; } } public long RetainedControlBytes { get { lock (_sync) return _controlBytes; } } /// Counts retained import routes by configured connection, without exposing node or secret labels. public IReadOnlyDictionary CaptureSourceCounts() { lock (_sync) return _bindings.Values.Where(x => x.Route.DriverInstanceId.StartsWith("grpc-data:", StringComparison.Ordinal)) .GroupBy(x => x.Route.DriverInstanceId[10..], StringComparer.OrdinalIgnoreCase) .ToDictionary(x => x.Key, x => x.Count(), StringComparer.OrdinalIgnoreCase); } private static (DataRealm, string) Key(ProjectedValueRoute route) => (route.Realm, route.LocalIdentifier); private bool Authorized(ProjectedValueRoute route) { try { route.Serving.Validate(requireEpochs: true); if (string.IsNullOrWhiteSpace(route.DriverInstanceId) || route.DriverInstanceId.Length > 512 || route.Serving.NodeId.Length > 512 || route.Serving.Incarnation.Length > 256 || route.Serving.Role.Length > 32) return false; return route.PublicationId != Guid.Empty && route.ProjectionGeneration > 0 && route.Serving.ServingGeneration > 0 && ProjectedDataIds.TryParseDependencyReference(route.DependencyReference, out var realm, out var id) && realm == route.Realm && id == route.LocalIdentifier && _authority(route); } catch (Exception) { return false; } } public bool TryBind(ProjectedValueRoute route) { ArgumentNullException.ThrowIfNull(route); if (!Authorized(route)) return false; lock (_sync) { if (_disposed) return false; var bytes = RouteCharge(route); if (_trackedReferences.TryGetValue(route.DependencyReference, out var held)) { var additional = Math.Max(0, bytes - held); if (additional > _maximumControlBytes - _controlBytes) return false; _trackedReferences[route.DependencyReference] = Math.Max(held, bytes); _controlBytes += additional; } else { if (_trackedReferences.Count >= _maximumRoutes || bytes > _maximumControlBytes - _controlBytes) return false; _trackedReferences.Add(route.DependencyReference, bytes); _controlBytes += bytes; } if (!_bindings.TryGetValue(Key(route), out var current) || current.Route != route) _bindings[Key(route)] = new(route); return true; } } internal static long RouteCharge(ProjectedValueRoute route) => checked(1024L + 8L * (route.DependencyReference.Length + route.LocalIdentifier.Length + route.DriverInstanceId.Length + route.Serving.NodeId.Length + route.Serving.Incarnation.Length + route.Serving.Role.Length)); private bool Current(Binding binding) { lock (_sync) if (_disposed || !_bindings.TryGetValue(Key(binding.Route), out var now) || !ReferenceEquals(binding, now)) return false; return Authorized(binding.Route); } private sealed class Witness(ActorProjectedValuePublisher owner, Binding binding, IProjectedSamplePublicationProof source, object identity, DataAgeBounds ageBounds, long receivedTimestamp, TimeSpan? maximumAge) : IProjectedSamplePublicationProof { public object SourceIdentity => identity; public bool IsSourceValid { get { try { return owner.Current(binding) && source.IsSourceValid && owner.OwnsIdentity(binding, identity); } catch (Exception) { return false; } } } public bool IsValid { get { try { if (!IsSourceValid || !source.IsValid) return false; if (maximumAge is not { } limit) return owner.OwnsIdentity(binding, identity); var elapsed = Clock.GetElapsedTime(receivedTimestamp); return limit > TimeSpan.Zero && elapsed >= TimeSpan.Zero && ageBounds.Advance(elapsed).IsFresh(limit) && owner.OwnsIdentity(binding, identity); } catch (Exception) { return false; } } } public TimeProvider Clock => source.Clock; public void Invalidate() { // An expired sample can remain queued across a compatible authority // handoff. Discard that evidence without retiring the independently live // logical source which may already own a fresh successor baseline. if (ProjectedEvidenceRetirement.CanDrop(source) && IsSourceValid) return; try { source.Invalidate(); } finally { owner.RetireWitness(binding, identity); } } } private bool OwnsIdentity(Binding binding, object identity) { lock (_sync) return !_disposed && _bindings.TryGetValue(Key(binding.Route), out var current) && ReferenceEquals(current, binding) && ReferenceEquals(binding.PublicationIdentity, identity); } private void RetireWitness(Binding binding, object identity) { var removed = false; lock (_sync) if (OwnsIdentity(binding, identity)) { _bindings.Remove(Key(binding.Route)); _retiredReferences.Add(binding.Route.DependencyReference); removed = true; } if (removed) NotifyRetirements(); } private Witness WitnessFor(Binding binding, ProjectedValueUpdate update) { var source = update.SourceProof; var sourceIdentity = source.SourceIdentity ?? throw new InvalidOperationException("Source identity is required."); lock (_sync) { if (!ReferenceEquals(binding.SourceIdentity, sourceIdentity)) { binding.SourceIdentity = sourceIdentity; binding.PublicationIdentity = new object(); } return new(this, binding, source, binding.PublicationIdentity!, update.OriginAgeBounds, update.ReceivedTimestamp, update.MaximumSampleAge); } } private void Invalidate(IEnumerable updates) { foreach (var update in updates) { if (ProjectedEvidenceRetirement.CanDrop(update.SourceProof) && IsCurrent(update.Route)) continue; try { update.SourceProof.Invalidate(); } catch (Exception) { } Retire(update.Route); } } private IActorRef? Host() { try { return _host(); } catch (Exception) { return null; } } private void SweepQueued() { ProjectedPublicationBatch[] pending; lock (_sync) { if (_disposed) return; pending = _pending.ToArray(); } foreach (var batch in pending) if (!batch.IsValid) batch.AbortQueued(); NotifyRetirements(); } public bool TryPublish(IReadOnlyList updates) { ArgumentNullException.ThrowIfNull(updates); if (updates.Count == 0 || updates.Count > _maximumRoutes) { Invalidate(updates); return false; } var captured = updates.ToArray(); var bindings = new Binding[captured.Length]; long charge = 256; try { if (captured.Select(update => Key(update.Route)).Distinct().Count() != captured.Length) throw new ArgumentException("Duplicate projected route."); for (var i = 0; i < captured.Length; i++) { var update = captured[i]; update.OriginAgeBounds.Validate(); if (!ReferenceEquals(update.SourceProof.Clock, _clock) || !update.SourceProof.IsValid || update.SourceVersion is <= 0 || _clock.GetElapsedTime(update.ReceivedTimestamp) < TimeSpan.Zero || !Authorized(update.Route)) return Refused(); charge = checked(charge + 512 + OwnedDataSample.Estimate(update.Snapshot.Value)); } var admitted = false; lock (_sync) { if (!_disposed && charge <= _maximumBytes - _pendingBytes) { admitted = true; for (var i = 0; i < captured.Length; i++) if (!_bindings.TryGetValue(Key(captured[i].Route), out bindings[i]!) || bindings[i].Route != captured[i].Route) { admitted = false; break; } if (admitted) _pendingBytes += charge; } } if (!admitted) return Refused(); } catch (Exception error) when (error is ArgumentException or OverflowException) { return Refused(); } ProjectedPublicationBatch? batch = null; try { var writes = captured.Select((update, i) => new ProjectedValueWrite(update.Route.Realm, update.Route.LocalIdentifier, update.Route.ProjectionGeneration, update.Route.Serving, update.Snapshot with { Value = OwnedDataSample.CopyLegacy(update.Snapshot.Value) }, update.OriginAgeBounds, update.ReceivedTimestamp, WitnessFor(bindings[i], update), update.IsCompleteSnapshot, update.SourceVersion)).ToArray(); batch = new(writes, captured.Select(update => update.Route).ToArray(), Complete, ForwardToMux); lock (_sync) { // Enqueue is the publication order boundary. Completed slots may be reused in // ownership sets; their enumeration order never determines sample order. batch.QueueSequence = checked(++_nextQueueSequence); _pending.Add(batch); } if (!batch.IsValid || Host() is not { } host) { batch.AbortQueued(); return false; } NotifyValues(host); return true; } catch (Exception) { if (batch is not null) batch.AbortQueued(); else { lock (_sync) _pendingBytes -= charge; Invalidate(captured); } return false; } bool Refused() { Invalidate(captured); return false; } void Complete(ProjectedPublicationBatch completed) { lock (_sync) { _pending.Remove(completed); _sdkPending.Remove(completed); _pendingBytes -= charge; } } } private void NotifyValues(IActorRef host) { lock (_sync) { if (_pending.Count == 0 || _valueWakePending && Equals(host, _valueHost)) return; _valueHost = host; _valueWakePending = true; } host.Tell(new DriverHostActor.DrainProjectedValues(this)); } internal ProjectedPublicationBatch[] TakeQueuedValues(IActorRef host) { lock (_sync) { if (!Equals(host, _valueHost)) return []; _valueWakePending = false; return _pending.OrderBy(batch => batch.QueueSequence).Where(batch => batch.TryForward()).ToArray(); } } internal void EnqueueForSdk(ProjectedPublicationBatch batch, IActorRef sdk, IActorRef? mux) { var wake = false; lock (_sync) { if (!batch.IsQueued) return; _sdkPending.Add(batch); if (!_sdkWakePending || !Equals(_sdkActor, sdk)) { _sdkActor = sdk; _sdkWakePending = true; wake = true; } } if (wake) sdk.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.DrainProjectedValues(this, mux)); } internal ProjectedPublicationBatch[] TakeSdkValues(IActorRef sdk) { lock (_sync) { if (!Equals(_sdkActor, sdk)) return []; _sdkWakePending = false; var result = _sdkPending.Where(batch => batch.IsQueued).OrderBy(batch => batch.QueueSequence).ToArray(); _sdkPending.Clear(); return result; } } private bool ForwardToMux(IActorRef mux, IReadOnlyList routes, IReadOnlyList writes) { ProjectedCoalescingMailbox mailbox; lock (_sync) { if (_disposed) return false; if (_muxMailbox is null || !Equals(_muxTarget, mux)) { _muxMailbox?.Dispose(); _muxTarget = mux; _muxMailbox = new(mux, queue => new ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags.DependencyMuxActor.DrainProjectedBatch(queue), _maximumBytes, _maximumRoutes); } mailbox = _muxMailbox; } try { var items = routes.Select((route, index) => (route.DependencyReference, new ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags.DependencyMuxActor.ProjectedDependency(route.PublicationId.ToString("N"), route.DependencyReference, writes[index]), checked(512L + OwnedDataSample.Estimate(writes[index].Snapshot.Value) + 2L * route.DependencyReference.Length))).ToArray(); return mailbox.TryOffer(items); } catch (Exception error) when (error is ArgumentException or OverflowException or IndexOutOfRangeException) { return false; } } public void Retire(ProjectedValueRoute route) { var removed = false; lock (_sync) if (_bindings.TryGetValue(Key(route), out var binding) && binding.Route == route) { _bindings.Remove(Key(route)); _retiredReferences.Add(route.DependencyReference); removed = true; } if (removed) NotifyRetirements(); } internal bool IsCurrent(ProjectedValueRoute route) { lock (_sync) if (_disposed || !_bindings.TryGetValue(Key(route), out var binding) || binding.Route != route) return false; return Authorized(route); } internal string[] TakeRetiredReferences(IActorRef host) { lock (_sync) { if (!Equals(host, _retirementHost)) return []; var references = _retiredReferences.ToArray(); _retiredReferences.Clear(); _retirementWakePending = false; foreach (var reference in references) if (ProjectedDataIds.TryParseDependencyReference(reference, out var realm, out var identifier) && !_bindings.ContainsKey((realm, identifier)) && _trackedReferences.Remove(reference, out var bytes)) _controlBytes -= bytes; return references; } } /// Rearms outstanding retirement after the owning actor starts or restarts. public void HostActivated(IActorRef host) { lock (_sync) { _retirementHost = host; _retirementWakePending = false; _valueHost = host; _valueWakePending = false; } NotifyRetirements(host); NotifyValues(host); } private void NotifyRetirements(IActorRef? activated = null) { var host = activated ?? Host(); if (host is null) return; lock (_sync) { if (_retiredReferences.Count == 0 || _retirementWakePending && Equals(host, _retirementHost)) return; _retirementHost = host; _retirementWakePending = true; } host.Tell(new DriverHostActor.DrainProjectedRetirements(this)); } public void Dispose() { ProjectedPublicationBatch[] pending; ProjectedValueRoute[] routes; lock (_sync) { if (_disposed) return; _disposed = true; routes = _bindings.Values.Select(binding => binding.Route).ToArray(); _bindings.Clear(); foreach (var route in routes) _retiredReferences.Add(route.DependencyReference); pending = _pending.ToArray(); } _cleanup.Dispose(); _muxMailbox?.Dispose(); foreach (var batch in pending) batch.AbortQueued(); NotifyRetirements(); } } /// Queued ownership may abort; physical sink ownership remains charged until completion. internal sealed class ProjectedPublicationBatch { internal long QueueSequence { get; set; } private int _state; private int _forwarded; private IReadOnlyList _writes; private IReadOnlyList _routes; private readonly Action _release; private readonly Func, IReadOnlyList, bool> _forward; internal ProjectedPublicationBatch(IReadOnlyList writes, IReadOnlyList routes, Action release, Func, IReadOnlyList, bool> forward) { _writes = writes; _routes = routes; _release = release; _forward = forward; } internal bool ForwardToMux(IActorRef mux) => _forward(mux, Routes, Writes); internal IReadOnlyList Writes => Volatile.Read(ref _writes); internal IReadOnlyList Routes => Volatile.Read(ref _routes); internal bool IsQueued => Volatile.Read(ref _state) == 0; internal bool TryForward() => IsQueued && Interlocked.Exchange(ref _forwarded, 1) == 0; internal bool IsValid => Volatile.Read(ref _state) != 2 && Writes.All(value => value.Proof.IsValid); internal bool TryBegin() => Interlocked.CompareExchange(ref _state, 1, 0) == 0; internal void AbortQueued() { if (Interlocked.CompareExchange(ref _state, 2, 0) != 0) return; var writes = Interlocked.Exchange(ref _writes, Array.Empty()); Interlocked.Exchange(ref _routes, Array.Empty()); Invalidate(writes); _release(this); } internal void Complete(bool success) { if (Interlocked.CompareExchange(ref _state, 2, 1) != 1) return; var writes = Interlocked.Exchange(ref _writes, Array.Empty()); Interlocked.Exchange(ref _routes, Array.Empty()); if (!success) Invalidate(writes); _release(this); } private static void Invalidate(IEnumerable writes) { foreach (var value in writes) try { value.Proof.Invalidate(); } catch (Exception) { } } }