Files
ucvl-zonghengjia-open-source/windows/ConnectionHealthPolicy.cs

70 lines
3.3 KiB
C#

namespace UCVL.VPNPlus;
// Advisory after connection only; never an Internet-site gate in StartAsync.
// A delayed probe must not undo a user's disconnect or judge a different core.
internal sealed class ConnectionHealthPolicy
{
internal enum Decision { Ignore, Keep, Repair, PendingAdvisory, WebsiteUnavailable, TailnetEgressUnverified, Switch }
internal long Revision { get; private set; }
internal int Failures { get; private set; }
internal bool HasBeenHealthy { get; private set; }
private long _nextProbe;
private Decision? _advisoryCandidate;
internal void Invalidate()
{
Revision++;
_advisoryCandidate = null;
}
internal void BeginCore(long now)
{
Invalidate(); Failures = 0; HasBeenHealthy = false;
_nextProbe = now + 5_000;
}
internal void ResetFailures() => Failures = 0;
internal bool IsDue(long now, bool running) => !running || now >= _nextProbe;
internal Decision Observe(long revision, int? testedCore, int? currentCore,
bool wanted, bool busy, bool transitioning, bool exiting, bool healthy, long now, bool proxyHealthy = false,
bool activeTailnet = false, bool businessUnavailable = false)
{
if (revision != Revision || testedCore != currentCore || !wanted || busy || transitioning || exiting)
return Decision.Ignore;
if (healthy && currentCore is not null) {
_advisoryCandidate = null;
HasBeenHealthy = true; Failures = 0; _nextProbe = now + 20_000;
return Decision.Keep;
}
if (currentCore is not null && businessUnavailable && proxyHealthy) {
Failures = 0; _nextProbe = now + 20_000;
const Decision advisory = Decision.WebsiteUnavailable;
var confirmed = _advisoryCandidate == advisory;
_advisoryCandidate = advisory;
return confirmed ? advisory : Decision.PendingAdvisory;
}
_advisoryCandidate = null;
if (proxyHealthy && currentCore is not null) {
// Do not punish/restart a working node for a local smart-rule fault.
// The UI must show degraded routing, not declare the business path healthy.
Failures = 0; _nextProbe = now + 20_000;
return Decision.Repair;
}
if (currentCore is not null && activeTailnet) {
// A verified proxy can survive one failed round without moving.
// Three rounds with no forced HTTPS response request same-node fallback.
_advisoryCandidate = null;
_nextProbe = now + 20_000;
return ++Failures switch {
1 => Decision.PendingAdvisory,
2 => Decision.TailnetEgressUnverified,
_ => Decision.Switch,
};
}
Failures++;
_nextProbe = now + (HasBeenHealthy ? 20_000 : 5_000);
// Established connections retain tolerance for two transient rounds.
// An unverified newly selected node gets one retry, not a minute of
// false connected state; a dead core does not wait for HTTP timeouts.
return currentCore is null || Failures >= (HasBeenHealthy ? 3 : 2)
? Decision.Switch : Decision.Keep;
}
}