Files
ucvl-zonghengjia-open-source/windows/NodeHealthProbe.cs
T

155 lines
7.5 KiB
C#
Raw Normal View History

using System.Net;
namespace UCVL.VPNPlus;
// An advisory probe for the explicitly retained automatic failover feature.
// It is NOT part of 0.2.5's connection transaction and never changes routes.
internal static class NodeHealthProbe
{
internal readonly record struct Observation(bool BusinessHealthy, bool TransportReachable, string? Diagnostic = null);
internal readonly record struct Report(bool BusinessHealthy, bool TransportReachable);
internal static bool Accepts(int target, int status) => target == 0
? status is 200 or 204
: status is >= 200 and < 500;
internal static bool OverallHealthy(IReadOnlyList<bool> results) =>
results.Count >= 3 && results[2] && (results[0] || results[1]);
internal static bool AcceptsTransportStatus(int status) => status is >= 100 and <= 599;
private static async Task<Observation> Observed(Task<Observation> probe)
{
try { return await probe.ConfigureAwait(false); }
catch { return default; }
}
internal static async Task<bool> AggregateTransportAsync(IReadOnlyList<Task<Observation>> probes,
CancellationToken token, Action cancelRemaining)
{
var pending = probes.Select(Observed).ToList();
try
{
token.ThrowIfCancellationRequested();
while (pending.Count > 0)
{
var finished = await Task.WhenAny(pending).WaitAsync(token).ConfigureAwait(false);
pending.Remove(finished);
var observation = await finished.ConfigureAwait(false);
token.ThrowIfCancellationRequested();
if (observation.TransportReachable) return true;
}
return false;
}
finally { cancelRemaining(); }
}
internal static async Task<Report> AggregateReportAsync(IReadOnlyList<Task<Observation>> probes,
CancellationToken token, Action cancelRemaining)
{
var observations = probes.Select(Observed).ToArray();
async Task<bool> BusinessAsync(Task<Observation> probe) => (await probe.ConfigureAwait(false)).BusinessHealthy;
try
{
token.ThrowIfCancellationRequested();
var business = AggregateAsync(observations.Select(BusinessAsync).ToArray(), token, () => { });
var transport = AggregateTransportAsync(observations, token, () => { });
await Task.WhenAll(business, transport).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
return new(await business.ConfigureAwait(false), await transport.ConfigureAwait(false));
}
finally { cancelRemaining(); }
}
internal static async Task<bool> AggregateAsync(IReadOnlyList<Task<bool>> probes,
CancellationToken token, Action cancelRemaining)
{
async Task<bool> ResultAsync(Task<bool> probe)
{
try { return await probe.ConfigureAwait(false); }
catch { return false; }
}
// Observe every probe even after an early verdict. Cancellation or a
// late HTTP exception from a losing probe must not escape unobserved.
var observations = probes.Select(ResultAsync).ToArray();
try
{
token.ThrowIfCancellationRequested();
if (observations.Length < 3) return false;
var results = new bool?[3];
var pending = Enumerable.Range(0, 3).ToList();
while (pending.Count > 0)
{
var completed = await Task.WhenAny(pending.Select(index => observations[index]))
.WaitAsync(token).ConfigureAwait(false);
var index = pending.First(index => observations[index] == completed);
results[index] = await completed.ConfigureAwait(false);
pending.Remove(index);
token.ThrowIfCancellationRequested();
// Codex is mandatory; either independent target is sufficient.
// Stop only once that same predicate is proved or impossible.
if (results[2] == false || results[0] == false && results[1] == false) return false;
if (results[2] == true && (results[0] == true || results[1] == true)) return true;
}
return false;
}
finally
{
cancelRemaining();
}
}
internal static async Task<bool> CheckAsync(CancellationToken token, int proxyPort = 0)
=> (await CheckReportAsync(token, proxyPort).ConfigureAwait(false)).BusinessHealthy;
internal static async Task<bool> CheckTransportAsync(CancellationToken token, int proxyPort)
=> (await CheckReportAsync(token, proxyPort, transportOnly: true).ConfigureAwait(false)).TransportReachable;
internal static async Task<Report> CheckReportAsync(CancellationToken token, int proxyPort = 0, bool transportOnly = false)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
timeout.CancelAfter(TimeSpan.FromSeconds(15));
using var client = new HttpClient(new SocketsHttpHandler {
UseProxy = true, Proxy = new WebProxy(proxyPort > 0 ? $"socks5://127.0.0.1:{proxyPort}" : "http://127.0.0.1:10809"),
ConnectTimeout = TimeSpan.FromSeconds(8), AllowAutoRedirect = false,
}) { Timeout = Timeout.InfiniteTimeSpan };
var targets = new[] {
(Name: "google", Url: "https://www.google.com/generate_204"),
(Name: "openai", Url: "https://api.openai.com/v1/models"),
(Name: "codex", Url: "https://chatgpt.com/backend-api/codex/models"),
};
var probes = targets.Select(async (target, index) => {
try {
using var response = await client.GetAsync(target.Url, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
var status = (int)response.StatusCode;
return new Observation(Accepts(index, status), AcceptsTransportStatus(status), $"http_{status}");
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
catch (OperationCanceledException) { return new Observation(false, false, "timeout"); }
catch (HttpRequestException ex) { return new Observation(false, false, ex.HttpRequestError.ToString()); }
catch { return new Observation(false, false, "request_failed"); }
}).ToArray();
// Retain the stricter business-site diagnostic separately. A valid
// TLS/HTTP response through the forced proxy, including 5xx, proves
// transport reachability without claiming the target service is healthy.
if (transportOnly)
return new(false, await AggregateTransportAsync(probes, token, timeout.Cancel).ConfigureAwait(false));
try
{
var report = await AggregateReportAsync(probes, token, () => { }).ConfigureAwait(false);
if (!report.BusinessHealthy)
{
var path = proxyPort > 0 ? "forced_proxy" : "ordinary";
var outcomes = targets.Select((target, index) =>
{
var probe = probes[index];
var result = probe.IsCompletedSuccessfully ? probe.Result.Diagnostic : "pending";
return $"{target.Name}={result}";
});
AppPaths.WriteLog($"site_probe path={path} transport={report.TransportReachable} {string.Join(" ", outcomes)}");
}
return report;
}
finally { timeout.Cancel(); }
}
}