namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; // Active controls bracket each generation change. Overflow poisons the signal // permanently, rather than allowing a wrapped generation to match a snapshot. internal sealed class PartitionControlSignal { private long _generation; private long _active; private int _poisoned; // Only the outer signal owns this additional lifecycle counter; its child is a leaf. internal PartitionControlSignal Quiet { get; } = null!; internal PartitionControlSignal() : this(true) { } private PartitionControlSignal(bool includeQuiet) { if (includeQuiet) Quiet = new PartitionControlSignal(false); } internal void BeginQuiet() { Begin(); Quiet.Begin(); } internal void EndQuiet() { Quiet.End(); End(); } internal void Begin() { if (Volatile.Read(ref _poisoned) != 0) return; if (Interlocked.Increment(ref _active) <= 0) { Interlocked.Exchange(ref _poisoned, 1); return; } if (Interlocked.Increment(ref _generation) < 0) Interlocked.Exchange(ref _poisoned, 1); } internal void End() { if (Volatile.Read(ref _poisoned) != 0) return; if (Interlocked.Increment(ref _generation) < 0) { Interlocked.Exchange(ref _poisoned, 1); return; } if (Interlocked.Decrement(ref _active) < 0) Interlocked.Exchange(ref _poisoned, 1); } internal bool TryCapture(out long stamp) { stamp = -1; if (Volatile.Read(ref _poisoned) != 0 || Volatile.Read(ref _active) != 0) return false; var generation = Volatile.Read(ref _generation); if (generation < 0 || Volatile.Read(ref _active) != 0 || Volatile.Read(ref _poisoned) != 0) return false; stamp = generation; return true; } internal bool Matches(long stamp) => stamp >= 0 && Volatile.Read(ref _poisoned) == 0 && Volatile.Read(ref _active) == 0 && Volatile.Read(ref _generation) == stamp && Volatile.Read(ref _active) == 0 && Volatile.Read(ref _poisoned) == 0; }