namespace UCVL.VPNPlus; internal interface IHandoverRuntime { string? BoundNetworkFingerprint { get; } bool CanRebindNetwork { get; } bool IsRunning { get; } Task SuspendForNetworkChangeAsync(CancellationToken token); Task RebindNetworkAsync(CancellationToken token); } // No control-plane HTTP, node penalty or saved credentials in this coordinator. // Rebind only the current, already-authorized in-memory configuration. internal sealed class NetworkHandover(IHandoverRuntime runtime, Func? clock = null) { internal enum Result { Unchanged, Settling, Offline, Recovered, Retry, Cancelled, SnapshotUnavailable } private string? _candidate; private bool _observed, _pending; private long _since, _retryAt; private int _failures, _revision; internal bool Pending => _pending; internal bool Settling { get; private set; } internal void Reset() { _revision++; _pending = _observed = Settling = false; _candidate = null; _retryAt = 0; _failures = 0; } internal async Task ObserveAsync(PhysicalUplink.Reading reading, long now, CancellationToken token) { token.ThrowIfCancellationRequested(); if (!reading.Success) return Result.SnapshotUnavailable; if (!runtime.CanRebindNetwork) { Reset(); return Result.Unchanged; } var fingerprint = PhysicalUplink.Fingerprint(reading.Network); if (!_pending && fingerprint is not null && fingerprint == runtime.BoundNetworkFingerprint) { _observed = Settling = false; _failures = 0; return Result.Unchanged; } Settling = true; if (!_observed || _candidate != fingerprint) { _observed = true; _candidate = fingerprint; _since = now; _retryAt = 0; } if (now - _since < 3_000) return Result.Settling; _pending = true; if (now < _retryAt) return Result.Retry; var revision = _revision; try { if (reading.Network is null) { // Preserve the config, but remove our capture while offline. One stop, // not repeated adapter deletion on every timer tick. if (runtime.IsRunning) await runtime.SuspendForNetworkChangeAsync(token); return Result.Offline; } await runtime.RebindNetworkAsync(token); if (revision != _revision || token.IsCancellationRequested) return Result.Cancelled; _pending = _observed = Settling = false; _retryAt = 0; _failures = 0; return Result.Recovered; } catch (OperationCanceledException) when (token.IsCancellationRequested) { return Result.Cancelled; } catch { if (revision != _revision) return Result.Cancelled; // Start backoff after a slow DNS/adapter failure, not before it. _retryAt = Math.Max(now, (clock ?? (() => Environment.TickCount64))()) + Math.Min(30_000, 5_000 * ++_failures); throw; } } }