using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// An immutable Warm verdict and its process-local change generation. public sealed record DataConnectionWarmRoleSnapshot(WarmRole? Role, long Generation); /// Publishes the active OPC UA publisher's actual Warm verdict under the shared dispatch fence. public sealed class DataConnectionWarmRoleView { private sealed record State(long Owner, DataConnectionWarmRoleSnapshot Snapshot); private State _state = new(0, new(null, 0)); private long _nextOwner; private bool _poisoned; public DataConnectionWarmRoleView(DataWriteDispatchFence dispatchFence) => DispatchFence = dispatchFence ?? throw new ArgumentNullException(nameof(dispatchFence)); public DataWriteDispatchFence DispatchFence { get; } public DataConnectionWarmRoleSnapshot Snapshot => Volatile.Read(ref _state).Snapshot; public WarmRole? CurrentRole => Snapshot.Role; public long Generation => Snapshot.Generation; /// Replaces the publisher owner and immediately withdraws the old verdict. public long RegisterOwner() { using (DispatchFence.Enter()) { var current = _state; if (_poisoned || _nextOwner == long.MaxValue || current.Snapshot.Generation == long.MaxValue) { Poison(); throw new InvalidOperationException("Warm role generation exhausted."); } var owner = ++_nextOwner; Volatile.Write(ref _state, new State(owner, new(null, current.Snapshot.Generation + 1))); return owner; } } /// Publishes only for the current owner; returns true when the verdict changes. public bool Publish(long owner, WarmRole role) { if (!Enum.IsDefined(role)) throw new ArgumentOutOfRangeException(nameof(role)); using (DispatchFence.Enter()) { var current = _state; if (_poisoned || owner == 0 || current.Owner != owner || current.Snapshot.Role == role) return false; if (current.Snapshot.Generation == long.MaxValue) { Poison(); return true; } Volatile.Write(ref _state, new State(owner, new(role, current.Snapshot.Generation + 1))); return true; } } /// Withdraws a current owner's verdict; a superseded owner cannot affect its successor. public bool RetireOwner(long owner) { using (DispatchFence.Enter()) { var current = _state; if (_poisoned || owner == 0 || current.Owner != owner) return false; if (current.Snapshot.Generation == long.MaxValue) { Poison(); return true; } Volatile.Write(ref _state, new State(0, new(null, current.Snapshot.Generation + 1))); return true; } } private void Poison() { _poisoned = true; Volatile.Write(ref _state, new State(0, new(null, long.MaxValue))); } }