67 lines
3.0 KiB
C#
67 lines
3.0 KiB
C#
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
/// <summary>An immutable Warm verdict and its process-local change generation.</summary>
|
|
public sealed record DataConnectionWarmRoleSnapshot(WarmRole? Role, long Generation);
|
|
|
|
/// <summary>Publishes the active OPC UA publisher's actual Warm verdict under the shared dispatch fence.</summary>
|
|
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;
|
|
|
|
/// <summary>Replaces the publisher owner and immediately withdraws the old verdict.</summary>
|
|
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;
|
|
}
|
|
}
|
|
/// <summary>Publishes only for the current owner; returns true when the verdict changes.</summary>
|
|
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;
|
|
}
|
|
}
|
|
/// <summary>Withdraws a current owner's verdict; a superseded owner cannot affect its successor.</summary>
|
|
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)));
|
|
}
|
|
}
|