namespace UCVL.VPNPlus; // One monotonic ten-minute check of the same authorized node. This pure policy // never touches networking. Only a failed ACTIVE Tailnet path requests fallback; // a recovered alternate is advisory and cannot replace a healthy domain session. internal sealed class TailnetReadinessPolicy { internal readonly record struct Context(long Epoch, int? CoreId, bool Wanted, bool Busy, bool Running, bool UsesTailnet, bool HasAuthorizedCandidate); internal readonly record struct ProbeTicket(long Generation, long Sequence, long Epoch, int CoreId); internal enum Result { Ignore, NotReady, Confirming, BecameReady, Ready, Fallback } internal const long IntervalMilliseconds = 10 * 60_000; private bool _bound, _inFlight, _usesTailnet; private long _generation, _sequence, _epoch, _nextDue; private int? _core; internal bool IsReady { get; private set; } internal long NextDue => _nextDue; internal void Reset() { _generation++; _bound = _inFlight = IsReady = false; _core = null; _nextDue = 0; } private static bool Eligible(Context context) => context.Wanted && context.Running && context.CoreId is not null && context.HasAuthorizedCandidate; private void Synchronize(Context context, long now) { if (!Eligible(context)) { Reset(); return; } if (!_bound || _epoch != context.Epoch || _core != context.CoreId || _usesTailnet != context.UsesTailnet) { Reset(); _bound = true; _epoch = context.Epoch; _core = context.CoreId; _usesTailnet = context.UsesTailnet; // The initial path is tested by NodeTransportConnector. Do not // repeat it immediately after the connection becomes established. _nextDue = now + IntervalMilliseconds; } } internal bool TryBegin(Context context, long now, out ProbeTicket ticket) { ticket = default; Synchronize(context, now); if (!Eligible(context) || context.Busy || _inFlight || now < _nextDue) return false; _inFlight = true; ticket = new(_generation, ++_sequence, context.Epoch, context.CoreId!.Value); return true; } internal Result Observe(ProbeTicket ticket, Context context, long now, bool reachable) { Synchronize(context, now); if (!_inFlight || ticket.Generation != _generation || ticket.Sequence != _sequence || ticket.Epoch != context.Epoch || ticket.CoreId != context.CoreId || !Eligible(context)) return Result.Ignore; _inFlight = false; _nextDue = now + IntervalMilliseconds; // Do not publish a result obtained while connection/authorization state // is being changed. A new ticket can retry after the normal cadence. if (context.Busy) return Result.Ignore; if (!reachable) { IsReady = false; return context.UsesTailnet ? Result.Fallback : Result.NotReady; } if (context.UsesTailnet) return Result.Ready; if (IsReady) return Result.Ready; IsReady = true; return Result.BecameReady; } }