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

102 lines
5.7 KiB
C#

using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Text.RegularExpressions;
namespace UCVL.VPNPlus;
// Ranks only explicit public nodes from the current authenticated profile. This
// is connection planning, not proof of proxy identity or permission to replace a
// healthy core. The caller must still validate the selected proxy after start.
internal static class PublicTailnetSelection
{
internal sealed record Candidate(ConfigResponse Response, long LatencyMilliseconds);
private static readonly Regex ValidSlug = new("^[a-z0-9][a-z0-9-]{0,79}$", RegexOptions.CultureInvariant);
internal static async Task<IReadOnlyList<Candidate>> RankAsync(
IEnumerable<NodeInfo> authorizedNodes, string routeMode,
Func<string, bool> coolingDown,
Func<string, CancellationToken, Task<ConfigResponse>> loadConfig,
Func<string, int, CancellationToken, Task<bool>> endpointProbe,
CancellationToken token, bool allowKnownEndpoints = false,
Action<string, string>? diagnostic = null, TimeSpan? budget = null)
{
token.ThrowIfCancellationRequested();
if (routeMode is not ("smart" or "global")) return [];
// Snapshot before asynchronous work: profile/cooldown state belongs to
// the caller, and private grants must never become public dispatch.
var nodes = authorizedNodes.Where(n => n is not null && n is not PrivateAuxiliaryNode
&& n.Slug is not null && n.Slug != "auto" && ValidSlug.IsMatch(n.Slug))
.DistinctBy(n => n.Slug, StringComparer.Ordinal)
.Where(n => !coolingDown(n.Slug)).Take(8).ToArray();
if (nodes.Length == 0) return [];
var milliseconds = Math.Clamp((budget ?? TimeSpan.FromSeconds(15)).TotalMilliseconds, 1, 15_000);
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
deadline.CancelAfter(TimeSpan.FromMilliseconds(milliseconds));
using var slots = new SemaphoreSlim(3, 3);
ApiException? authorizationFailure = null;
void Report(string slug, string reason)
{
// Fixed reason codes only, never exception messages or config JSON.
if (!Regex.IsMatch(reason, "^[a-z0-9_]{1,80}$", RegexOptions.CultureInvariant)) reason = "metadata_rejected";
try { diagnostic?.Invoke(slug, reason); } catch { /* Telemetry cannot alter connection planning. */ }
}
async Task<(Candidate Candidate, int Index)?> Read(NodeInfo node, int index)
{
var entered = false;
try
{
await slots.WaitAsync(deadline.Token).ConfigureAwait(false);
entered = true;
// WaitAsync also bounds a buggy callback that ignores its token.
var response = await loadConfig(node.Slug, deadline.Token).WaitAsync(deadline.Token).ConfigureAwait(false);
deadline.Token.ThrowIfCancellationRequested();
if (response?.Node is null || !string.Equals(response.Node.Slug, node.Slug, StringComparison.Ordinal))
{ Report(node.Slug, "response_node_mismatch"); return null; }
if (!string.Equals(response.RouteMode, routeMode, StringComparison.Ordinal))
{ Report(node.Slug, "response_route_mismatch"); return null; }
var prepared = TailnetTransport.TryPrepare(response, out var reason, allowKnownEndpoints);
if (prepared is null) { Report(node.Slug, reason); return null; }
var address = TailnetTransport.Address(prepared);
var port = TailnetTransport.Port(prepared);
if (address is null || port is < 1 or > 65535)
{ Report(node.Slug, "prepared_endpoint_invalid"); return null; }
using var probeDeadline = CancellationTokenSource.CreateLinkedTokenSource(deadline.Token);
probeDeadline.CancelAfter(TimeSpan.FromSeconds(3));
var elapsed = Stopwatch.StartNew();
var available = await endpointProbe(address, port, probeDeadline.Token)
.WaitAsync(probeDeadline.Token).ConfigureAwait(false);
probeDeadline.Token.ThrowIfCancellationRequested();
if (!available) { Report(node.Slug, "endpoint_unreachable"); return null; }
Report(node.Slug, "endpoint_reachable");
return (new Candidate(response, Math.Max(0, elapsed.ElapsedMilliseconds)), index);
}
catch (ApiException error) when (error.StatusCode is 401 or 403)
{
// Never turn expired/revoked authorization into another node or
// public fallback. Cancel sibling work, then propagate unchanged.
Interlocked.CompareExchange(ref authorizationFailure, error, null);
deadline.Cancel();
Report(node.Slug, "authorization_rejected");
return null;
}
catch (OperationCanceledException) when (!token.IsCancellationRequested)
{ Report(node.Slug, "selection_or_probe_deadline"); return null; }
catch (OperationCanceledException) { throw; }
catch (Exception)
{ Report(node.Slug, "config_or_probe_unavailable"); return null; }
finally { if (entered) slots.Release(); }
}
var readings = await Task.WhenAll(nodes.Select(Read)).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
if (authorizationFailure is not null) ExceptionDispatchInfo.Capture(authorizationFailure).Throw();
return readings.Where(r => r is not null).Select(r => r!.Value)
.OrderBy(r => r.Candidate.LatencyMilliseconds).ThenBy(r => r.Index)
.Select(r => r.Candidate).ToArray();
}
}